[英]ActiveModel Serializer for complicated associations
我有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
我在加载: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
依次对: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
但是, 从不使用API::RecipientSerializer
,而是返回整个:recipient
。 我究竟做错了什么?
另外,以下是API::RecipientSerializer
用于以下方面:
class API::RecipientSerializer < ActiveModel::Serializer
attributes :id
end
两个问题:
ActiveModel::Serializer.config.default_includes = '**'
。 attributes
添加关系(从NotificationSerializer
attributes
中删除:recipient
)。 这可能行得通,因为您的关系将覆盖该属性,但是没有理由让它们吵架。 编辑 :由于设置default_includes
似乎存在问题,因此在呈现最终结果时需要特定的一个:
render json: user, include: ['notifications', 'notifications.recipient'], status: :ok
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.