【问题标题】:ActiveModel Serializer for complicated associations用于复杂关联的 ActiveModel 序列化程序
【发布时间】:2019-05-01 15:10:47
【问题描述】:

我有 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

【问题讨论】:

  • 如果将has_many :notifications, foreign_key: :recipient_id, each_serializer: API::NotificationSerializer 更改为has_many :notifications, foreign_key: :recipient_id, serializer: API::NotificationSerializer 会发生什么?通知是否正确序列化? (只有类中序列化的属性?)

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


【解决方案1】:

两个问题:

  1. 检查此link。如果您希望关系保持递归呈现(或在序列化对象时将其设置为您需要的任何值),则需要设置 ActiveModel::Serializer.config.default_includes = '**'
  2. 不要向attributes 添加关系(从attributes 中的NotificationSerializer 中删除:recipient)。这可能有效,因为您的关系会覆盖该属性,但没有理由让他们打架。

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

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

【讨论】:

  • 我只能通过使用您的链接中的信息,特别是 render json: user, include: ['notifications', 'notifications.recipient'], status: :ok 来使其工作。如果您在答案中包含此内容,我可以接受
  • @JeremyThomas 这真的很奇怪。设置ActiveModel::Serializer.config.default_includes后是否重启过应用?
  • 我不确定,它一直对我有用(类似question)。我将在答案中添加具体包含。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-29
  • 1970-01-01
  • 2018-04-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多