Search code examples
ruby-on-railspolymorphic-associationsactive-model-serializers

Ruby on Rails: set specific serializer for polymorphic association


I'm trying to override the default serializer for a polymorphic relationship. I have:

class NotificationListSerializer < ActiveModel::Serializer
  attributes :id, :title
  belongs_to :notifiable, polymorphic: true
end

If notifiable is an Organization, the organization is serialized with OrganizationSerializer. If notifiable is a Group, the group is serialized with GroupSerializer. This makes perfect sense, but how can I specify a different serializer, depending on the class?

For example, if notifiable is an Organization, I would like to use SparseOrganizationSerializer instead of OrganizationSerializer. How can I achieve this?

I'm pretty sure this is documented, but I'm having a hard time following and finding any examples.

From the documentation:

Polymorphic Relationships

Polymorphic relationships are serialized by specifying the relationship, like any other association. For example:

class PictureSerializer < ActiveModel::Serializer
  has_one :imageable
end

You can specify the serializers by overriding serializer_for. For more context about polymorphic relationships, see the tests for each adapter.

Overriding association serializer lookup

If you want to define a specific serializer lookup for your associations, you can override the ActiveModel::Serializer.serializer_for method to return a serializer class based on defined conditions.

class MySerializer < ActiveModel::Serializer
  def self.serializer_for(model, options)
    return SparseAdminSerializer if model.class == 'Admin'
    super
  end
  # the rest of the serializer
end

Solution

  • You can use belongs_to :notifiable with &block option to specify fit serializer there.