I'm trying to use the Active Model Serializer gem with my API, although I am struggling with something I thought would be pretty simple.
All my JSON responses are in a wrapped format, with every response having a top level message and status property, the data is within the content property. Every JSON response follows this format.
Example
{
  'status': statuscode,
  'message': message,
  'content': { 'object':obj }
}
The contents of the "content" property is where I would like to place the output of the Serializer. My lists of articles, etc.
I cannot figure out how to do this though?
Any help would be greatly appreciated.
IF You dont mind your status and messages hashes being inside a hash you can use a meta key.
(from 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!" }
  ]
}
Or if you need them to be top level keys you can SubClass ArraySerializer and overwrite as_json to allow it to merge in your keys.
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 
then just
render :json @object, :serializer => YourCustomArraySerializer
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With