活动模型序列化程序关联,除非 object.user == current_user

Active model serializer association unless object.user == current_user

我有一个 User 模型和一个 Employment 模型,如下所示:

Class User
 has_many :employments

Class Employment
 belongs_to :user

我正在通过 Active model serializer 提供 JSON api,如下所示:

class EmploymentSerializer < ActiveModel::Serializer
  attributes :id
  has_one :user

class UserSerializer < ActiveModel::Serializer
  attributes :id

一切正常。问题是:

当 current_user 是雇主时,我会使用用户关联加载工作,这很好用。当 current_user 不是 雇主时,我想将 属于 的职位加载给用户。

作为 EmploymentSerializer has_one :user,这会导致递归查询,其中 current_user has_one employment has_one current_user ad infinitum.

我试过在 EmploymentSerializer 中添加这个方法,但它不起作用:

def include_user?
  object.user != scope
end

如何加载 current_user 的工作?


解决方案

递归是由另一个序列化程序引起的,这个问题无关紧要。 AMS 正常工作。

belongs_to 一起,table 承担外键的责任。对于 has_one,table 希望另一个 table 持有它。由于您的 Employments table 具有指向 Users table 的外键,因此序列化程序中的 has_one :user 没有意义,因为它假定 Users table 有 Employments table.

的外键

一般来说,序列化程序关系通常应该反映模型,而您在这里将它们混淆了。当您的 Employment class 具有 belongs_to :user 关系时,您的序列化器应该具有相同的关系而不是相反的 has_one 关系。

编辑: Ryan.lee 的评论是正确的。在 active_model_serializers 中,has_one 确实与 belongs_to 相同,因为序列化器关心的是多样性,现在是所有权。但是由于 ActiveRecord 0.9 版也增加了对 belongs_to 的支持以反映 ActiveRecord 关联,因此这非常令人困惑。因此,当模型具有 belongs_to 时在序列化程序中使用 has_one 确实是正确的,但我建议在序列化程序中也使用 belongs_to 以避免混淆,因为它们 mean the same thing in the context of the serializer (but not ActiveRecord! )