活动模型序列化器和自定义JSON结构

我正在尝试使用我的API使用Active Model Serializer gem,尽管我正在努力处理我认为非常简单的事情。

我的所有JSON响应都是包装格式,每个响应都有一个顶级消息和状态属性,数据在content属性中。 每个JSON响应都遵循此格式。

{ 'status': statuscode, 'message': message, 'content': { 'object':obj } } 

“content”属性的内容是我想放置Serializer输出的地方。 我的文章列表等

虽然我无法弄清楚怎么做?

任何帮助将不胜感激。

如果你不介意你的状态和消息散列在散列内,你可以使用元键。

(来自https://github.com/rails-api/active_model_serializers/tree/0-8-stable )

render :json => @posts, :serializer => CustomArraySerializer, :meta => {:total => 10}

 => { "meta": { "total": 10 }, "posts": [ { "title": "Post 1", "body": "Hello!" }, { "title": "Post 2", "body": "Goodbye!" } ] } 

或者,如果您需要它们作为顶级键,您可以SubClass ArraySerializer并覆盖as_json以允许它在您的键中合并。

 def as_json(*args) @options[:hash] = hash = {} @options[:unique_values] = {} hash.merge!(@options[:top_level_keys]) if @options.key?(:top_level_keys) root = @options[:root] if root.present? hash.merge!(root => serializable_array) include_meta(hash) hash else serializable_array end end 

然后就是

render :json @object, :serializer => YourCustomArraySerializer