jademcosta
jademcosta

Reputation: 1528

Set Active Model serializer adapter per method

I'm trying to build an api-only app in rails 5. I'm using active model serializer (AMS). On my GET /users (UsersController#index) endpoint, I want the root json to have a "users" keyword before the json array of users.

If I set an initializer with ActiveModelSerializers.config.adapter = :json value, then I have the desired behavior.

But then, on the GET /users/1 the simple user json comes under the key user. I'd like to get rid of this key (in this case) and simply answer the user json as the root json.

The question is: how can I define the AMS adapter on a specific endpoint/response/method? Is that possible?

Upvotes: 3

Views: 2891

Answers (1)

jademcosta
jademcosta

Reputation: 1528

I should have read the manual :$

To override the "root" key, you have to provide a root: argument when you call the render method. If you are using the :json adapter on an initializer, it would be like this:

render json: @user, root: "admin" This would then generate a json like this:

{ "admin": { "id": 123, "email": "[email protected]" } }

If you want, you could also provide another key after the root: to set the adapter, like this: adapter: :json

So, the :attributes adapter doesn't have a root key. In order to remove the root key, you could do: render json: @user, root: "admin", adapter: :attributes

The official documentation is here and here

Upvotes: 5

Related Questions