[英]Serializer nested associations include only certain attributes
My serializer looks like this: 我的序列化器如下所示:
class RegistrationSerializer < ActiveModel::Serializer
attributes :id, :status
has_one :student
has_one :professor
has_one :course
end
Instead of returning all of the student data, I would like to do something like this: 我不想返回所有学生数据,而是想做这样的事情:
class RegistrationSerializer < ActiveModel::Serializer
attributes :id, :status
has_one :student [//only include :first_name]
has_one :professor
has_one :course
end
I dont want to edit student serializer directly because in other cases I will need all of the data. 我不想直接编辑学生序列化程序,因为在其他情况下,我将需要所有数据。
You can accomplish this by also specifying a serializer for student. 您还可以通过为学生指定序列化器来完成此操作。 Here is an example: 这是一个例子:
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
An alternative would be to flatten the data and have the student first name as a top level attribute: 另一种选择是将数据弄平,并以学生的名字作为顶层属性:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.