Ruby on rails 复杂关联的ActiveModel序列化程序

Ruby on rails 复杂关联的ActiveModel序列化程序,ruby-on-rails,serialization,active-model-serializers,Ruby On Rails,Serialization,Active Model Serializers,我有两个相关模型: class User < ActiveRecord::Base has_many :notifications, foreign_key: :recipient_id end class Notification < ActiveRecord::Base belongs_to :recipient, class_name: 'User' belongs_to :actor, class_name: 'User' belongs_t

我有两个相关模型:

class User < ActiveRecord::Base
    has_many :notifications, foreign_key: :recipient_id
end

class Notification < ActiveRecord::Base
    belongs_to :recipient, class_name: 'User'
    belongs_to :actor, class_name: 'User'
    belongs_to :notifiable, polymorphic: true
end
这反过来又为
:通知使用序列化程序:

class API::NotificationSerializer < ActiveModel::Serializer
    attributes :id, :recipient_id, :actor_id, :notifiable_id, :read_at, :action, :recipient, :actor, :notifiable_type

    belongs_to :recipient, serializer: API::RecipientSerializer
    belongs_to :actor
    belongs_to :notifiable, polymorphic: true
end
两个问题:

  • 看看这个。如果希望关系保持递归呈现,则需要设置
    ActiveModel::Serializer.config.default\u includes='**'
    (或者在序列化对象时将其设置为任何需要的值)
  • 不要将关系添加到
    属性
    (从
    通知序列化程序
    中的
    属性
    中删除
    :收件人
    )。这可能会起作用,因为您的关系将覆盖属性,但没有理由让他们争吵
  • 编辑:由于设置
    默认值_includes
    似乎有问题,因此在呈现最终结果时需要一个特定值:

    render json: user, include: ['notifications', 'notifications.recipient'], status: :ok
    

    如果将:
    有多个:通知,外键::收件人id,每个序列化程序:API::NotificationSerializer
    更改为
    有多个:通知,外键::收件人id,序列化程序:API::NotificationSerializer
    ?通知序列化是否正确?(只有在类中序列化的属性?)我只能通过使用链接中的信息,特别是
    render json:user,包括:['notifications','notifications.recipient',status::ok
    ,使它工作。如果你在回答中包括这一点,我可以接受it@JeremyThomas这真的很奇怪。在设置了
    ActiveModel::Serializer.config.default\u includes
    之后是否重新启动了应用程序?我不确定,它一直对我有效(类似)。我会在答案中加上具体的内容。
    class API::RecipientSerializer < ActiveModel::Serializer
        attributes :id
    end
    
    render json: user, include: ['notifications', 'notifications.recipient'], status: :ok