I am using 'active_model_serializers', '~> 0.10.6'
for rendering my API response. For my index
action I am doing this -
render json: @items, root: 'data', each_serializer: ItemsSerializer
but in my response, I am not getting the root key
- data
[
{
"id": 85,
"title": "B",
"source": "manager_added",
"shared": true,
"status": "suggested",
"item_type": "action_item",
"manager": {
"id": 2614,
"full_name": "Calvin H",
"first_name": "Calvin"
},
"reportee": {
"id": 2614,
"full_name": "Calvin H",
"first_name": "Calvin"
}
},
{
"id": 87,
"title": "D",
"source": "manager_added",
"shared": true,
"status": "suggested",
"item_type": "action_item",
"manager": {
"id": 2614,
"full_name": "Calvin H",
"first_name": "Calvin"
},
"reportee": {
"id": 2614,
"full_name": "Calvin H",
"first_name": "Calvin"
}
}
]
What I am doing wrong here?
The hardest part with AMS is finding it's right documentation. Based on the version you have mentioned, here's the documentation link: https://github.com/rails-api/active_model_serializers/tree/0-10-stable/docs
There are 3 adapters:
:default
(There won't be any root, basically root
key is useless, even if you add it):json
(This is what you need, you can add custom root
key. https://github.com/rails-api/active_model_serializers/blob/0-10-stable/docs/general/adapters.md#example-output-1):json_api
(Default root
key will be data
, but you can customize, maybe you can use this, but it will change the whole structure of your response json into something like: https://github.com/rails-api/active_model_serializers/blob/0-10-stable/docs/general/adapters.md#example-output-2)Answer:
render json: @items, root: 'data', adapter: :json, each_serializer: ItemsSerializer
or
render json: @items, adapter: :json, each_serializer: ItemsSerializer