[英]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. 如果notifiable
是组织,则组织使用OrganizationSerializer序列化。 If notifiable
is a Group, the group is serialized with GroupSerializer. 如果notifiable
是一个组,则该组使用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. 例如,如果notifiable
是组织,我想使用SparseOrganizationSerializer而不是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. 您可以通过重写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. 如果要为关联定义特定的序列化程序查找,可以覆盖ActiveModel :: Serializer.serializer_for方法,以根据定义的条件返回序列化程序类。
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 with&block选项在那里指定适合的序列化程序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.