简体   繁体   English

ActiveModel序列化程序,用于复杂的关联

[英]ActiveModel Serializer for complicated associations

I have 2 associated models: 我有2个关联的模型:

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

I use a serializer for when I load a :user : 我在加载:user时使用序列化器:

class API::UserSerializer < ActiveModel::Serializer
    attributes :id, :email, :auth_token, :location_id, :notifications

    has_many :notifications, foreign_key: :recipient_id, each_serializer: API::NotificationSerializer
end

which in turn uses a serializer for the :notifications : 依次对:notifications使用序列化器:

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

However, the API::RecipientSerializer is never used, and instead the whole :recipient is returned. 但是, 从不使用API::RecipientSerializer ,而是返回整个:recipient What am I doing wrong? 我究竟做错了什么?


Also, here is the API::RecipientSerializer for good measure: 另外,以下是API::RecipientSerializer用于以下方面:

class API::RecipientSerializer < ActiveModel::Serializer
    attributes :id
end

Two issues: 两个问题:

  1. Check this link . 检查此链接 You need to set ActiveModel::Serializer.config.default_includes = '**' if you want your relationships to keep rendering recursively (or set it to whatever you need whenever serializing objects). 如果希望您的关系保持递归渲染(或将其设置为序列化对象时所需的值),则需要设置ActiveModel::Serializer.config.default_includes = '**'
  2. Don't add relations to attributes (remove :recipient from attributes in NotificationSerializer ). 不要向attributes添加关系(从NotificationSerializer attributes中删除:recipient )。 This might work, as your relation will overwrite the attribute, but there's no reason to make them fight. 这可能行得通,因为您的关系将覆盖该属性,但是没有理由让它们吵架。

EDIT : As there seemed to be a problem with setting the default_includes , a specific one was needed while rendering the final result: 编辑 :由于设置default_includes似乎存在问题,因此在呈现最终结果时需要特定的一个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM