Serializer嵌套关联仅包含某些属性

时间:2018-04-04 03:24:55

标签: ruby ruby-on-rails-3 serialization

我的序列化器看起来像这样:

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

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

1 个答案:

答案 0 :(得分:2)

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

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