The benefits of Active Model Serializer over simply render json:?

Hi,

I have this Rails app that is purely an API app serving up JSON response. The Rails app made use of Active Model Serializer to prepare the JSON responses. The controller calls render with a serializer passed in. This design was already there.

My question is the what is whe benefits Active Model Serializer brings as opposed to preparing your payload and simply calling render json: @payload or something similar?

From my experience, Active Model Serializer is great for when you want to have more control of the json you are rendering. For instance, if you are rendering an Active Model record, like a User object, you might not want to expose all the User attributes… like access tokens or other sensitive information :slight_smile: … So you could create a @payload object and render that has json like this:

def show
  user = User.find(user_params)
  # handle nil user....
  @payload = {
    name: user.name,
    email: user.email,
    image_url: user.image_url
  }

  render json: @payload

But that could get pretty verbose if you want to expose a lot of fields… Also I would rather have that logic outside the controller to keep my controller skinny. So you can put the responsibility of rendering the JSON onto the object’s serializer:

def show
  user = User.find(user_params)
  # handle nil user....
  render json: user # this will render with the UserSerializer by default, but you can specify another serializer
end

Now its up to your serializer to expose the appropriate user attributes. This is a good resource for active model serializer #409 Active Model Serializers - RailsCasts

Hey thanks, that makes sense. Basically it’s just moving the preparation of the response payload from the controller to something else.