5

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.

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.