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 … So you could create a @payload object and render that has json like this:
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