How to implement multiple different serializers for same model using ActiveModel::Serializers?

odigity picture odigity · Sep 18, 2012 · Viewed 23.3k times · Source

Let's say you're implementing a REST API in Rails. When serving a collection, you might want to only include a few attributes:

/people

But when serving a single resource, you want to include all the attributes:

/people/1

I don't see how to do that using ActiveModel::Serializers, since the examples all use the pattern of defining one serializer per model (with a standard naming convention) and having AMS automatically use the right one in the controller when you do:

render json: @people

or:

render json: @person

Answer

phaedryx picture phaedryx · Oct 25, 2012

You can have multiple serializers for the same model, e.g.

class SimplePersonSerializer < ActiveModel::Serializer
  attributes :id, :name
end

and

class CompletePersonSerializer < ActiveModel::Serializer
  attributes :id, :name, :phone, :email
end

simple info for people in one controller:

render json: @people, each_serializer: SimplePersonSerializer

complete info for people in another:

render json: @people, each_serializer: CompletePersonSerializer

simple info for a single person:

render json: @person, serializer: SimplePersonSerializer

complete info for a single person:

render json: @person, serializer: CompletePersonSerializer