序列化程序嵌套关联仅包含某些属性

Serializer nested associations include only certain attributes

我的序列化程序如下所示:

class RegistrationSerializer < ActiveModel::Serializer
 attributes :id, :status
 has_one :student
 has_one :professor
 has_one :course
end

我不想返回所有学生数据,而是想做这样的事情:

class RegistrationSerializer < ActiveModel::Serializer
 attributes :id, :status
 has_one :student [//only include :first_name]
 has_one :professor
 has_one :course
end

我不想直接编辑学生序列化程序,因为在其他情况下我将需要所有数据。

您还可以通过为学生指定一个序列化程序来完成此操作。这是一个例子:

class RegistrationSerializer < ActiveModel::Serializer
 attributes :id, :status
 has_one :student, serializer: StudentSerializerFirstNameOnly
 has_one :professor
 has_one :course
end

class StudentSerializerFirstNameOnly < ActiveModel::Serializer
 attributes :first_name
end

另一种方法是展平数据并将学生的名字作为顶级属性:

class RegistrationSerializer < ActiveModel::Serializer
 attributes :id, :status, :student_first_name
 has_one :professor
 has_one :course

 def student_first_name
   object.student.first_name
 end
end