如果你不介意你的狀態和消息散列在哈希裏面,你可以使用元鍵。
(從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!" }
]
}
或者,如果你需要他們的頂級鍵,你可以繼承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