ruby-on-railsrubyactive-model-serializers

Adding global root key and specific root key for each serialized item with active model serializer


I am using active-model-serializer. I have a collection of objects that I need to return as a JSON in a special formal. Here's what I have written so far:

  @tickets = Ticket.where(status: "PLACED")
  render json: @tickets, root: 'placed', each_serializer: ItemSerializer

Here's my item serializer:

class ItemSerializer < ApplicationSerializer
  attributes :pool_id, :selections

  def root
   "params"
 end
end

Here's the response with the current code:

[{\"pool_id\":759,\"selections\":\"1/2/3/4/5/6/7/8\"}]

I want to be able to add a root key "params" to each element of the array and a global root key "placed" before the array, so the desired output would be:

{ "placed": [
    {
      "params": {
        "pool_id": 123,
        "selections": "1/1/1"
      }
    }
  ]
}

How can I achieve that with an active model serializer?


Solution

  • For the global root key, I needed to add adapter: :json to the render call

    render json: @tickets, root: 'placed', each_serializer: BatchItemSerializer, adapter: :json
    

    To add a key at the root of each serialized element, you can overwrite the attributes method in the serializer. In this specific case, you can do it like this:

      def attributes(*args)
        hash = super
        { params: hash }
      end