ruby-on-rails-3jsonrestactivemodel

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


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

Solution

  • To avoid mixing view concerns into your models (via serialized variations), use the view to render your JSON for each action, much like we do for HTML.

    jbuilder & rabl both fill this data templating need quite nicely.

    Update 2013-12-16: The ActiveModelSerializers library does support defining multiple serializers for one model, as @phaedryx answered later, by using custom serializers.