[英]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.