ActiveModel序列化程序,用于复杂的关联

时间:2018-11-29 14:14:58

标签: ruby-on-rails serialization active-model-serializers

我有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 个答案:

答案 0 :(得分:1)

两个问题:

  1. 选中此link。如果希望您的关系保持递归渲染,则需要设置ActiveModel::Serializer.config.default_includes = '**'(或在序列化对象时将其设置为所需的值)。
  2. 请勿将关系添加到attributes(从:recipient中的attributes删除NotificationSerializer)。这可能行得通,因为您的关系会覆盖该属性,但是没有理由让它们吵架。

编辑:由于设置default_includes似乎存在问题,因此在呈现最终结果时需要特定的一个:

render json: user, include: ['notifications', 'notifications.recipient'], status: :ok