ステータスとメッセージのハッシュがハッシュ内にあることを気にしない場合は、メタキーを使用できます。
( 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