我有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
答案 0 :(得分:1)
两个问题:
ActiveModel::Serializer.config.default_includes = '**'
(或在序列化对象时将其设置为所需的值)。attributes
(从:recipient
中的attributes
删除NotificationSerializer
)。这可能行得通,因为您的关系会覆盖该属性,但是没有理由让它们吵架。 编辑:由于设置default_includes
似乎存在问题,因此在呈现最终结果时需要特定的一个:
render json: user, include: ['notifications', 'notifications.recipient'], status: :ok