[英]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: 两个问题:
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 = '**'
。 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.