gpt4 book ai didi

ruby-on-rails - Ruby on Rails : set specific serializer for polymorphic association

转载 作者:行者123 更新时间:2023-12-04 06:09:52 28 4
gpt4 key购买 nike

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

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

notifiable是一个组织,该组织使用 OrganizationSerializer 进行序列化。如 notifiable是一个组,该组使用 GroupSerializer 进行序列化。这是完全有道理的,但是如何根据类指定不同的序列化程序?

例如,如果 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 选项来指定适合的序列化程序。

关于ruby-on-rails - Ruby on Rails : set specific serializer for polymorphic association,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43084037/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com