Question

I am using active_model_serializers to render a collection as JSON for ember-data consumption. All is ok when rendering a single item, but collection rendering consists as an array of items.

render json: @scenarios, status: :ok

gives:

[{"scenario":{"id":4,"name":"My sample scenario"}},{"scenario":{"id":5,"name":"Yet another sample scenario"}}]

but I would like to obtain:

{"scenarios": [{"id":4,"name":"My sample scenario"},{"id":5,"name":"Yet another sample scenario"}]}

What is the state of the art way to get a root key with all collection items, side-data, and so on? (the documentation is not that clear about this)

EDIT

The scenario serializer is currently as follow:

class ScenarioSerializer < ActiveModel::Serializer
  attributes :id, :name
end
Was it helpful?

Solution

Try the latest version. AMS uses the controller name as the key for an array. By default it should render like you showed above.

If your controller is not named ScenariosController, you can force the root element of the array like this:

render json: @scenarios, root: "scenarios", status: :ok
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top