簡體   English   中英

ActiveModel序列化程序,用於復雜的關聯

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

兩個問題:

  1. 檢查此鏈接 如果希望您的關系保持遞歸渲染(或將其設置為序列化對象時所需的值),則需要設置ActiveModel::Serializer.config.default_includes = '**'
  2. 不要向attributes添加關系(從NotificationSerializer attributes中刪除:recipient )。 這可能行得通,因為您的關系將覆蓋該屬性,但是沒有理由讓它們吵架。

編輯 :由於設置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