如果您不介意您的状态和消息散列在散列中,则可以使用元键。
(来自 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