Ruby on Rails: 为多态关联设置特定的序列化器

Ruby on Rails: set specific serializer for polymorphic association

我正在尝试覆盖多态关系的默认序列化程序。我有:

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

如果 notifiable 是一个组织,则该组织使用 OrganizationSerializer 进行序列化。如果 notifiable 是一个组,则该组使用 GroupSerializer 序列化。这很有意义,但是我如何根据 class?

指定不同的序列化程序

例如,如果 notifiable 是一个组织,我想使用 SparseOrganizationSerializer 而不是 OrganizationSerializer。我怎样才能做到这一点?

我很确定这已记录在案,但我很难理解并找到任何示例。

来自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

您可以使用 belongs_to :notifiable 和 &block 选项来指定合适的序列化程序。