在使用fast_jsonapi gem之前,我已经这样做了:
render json: school.to_json(include: [classroom: [:students]])
我的SchoolSerializer看起来像:
class SchoolSerializer
include FastJsonapi::ObjectSerializer
attributes :name, :description, :classroom
end
我如何让学生包括在JSON结果中?
还包括教室关联,但它显示所有属性,是否有办法将教室属性映射到ClassroomSerializer?
class School < ApplicationRecord
belongs_to :classroom
end
class Classroom < ApplicationRecord
has_many :students
end
答案 0 :(得分:2)
class SchoolSerializer
include FastJsonapi::ObjectSerializer
attributes :name, :description
belongs_to :classroom
end
# /serializers/classroom_serializer.rb
class ClassroomSerializer
include FastJsonapi::ObjectSerializer
attributes :.... #attributes you want to show
end
您还可以向您的学校模型添加其他关联,以访问学生。 像这样
has_many :students, through: :classroom
,然后将其直接包含在School序列化程序中。
更新:也请注意,您可以直接指向所需的序列化程序类。 (如果您想使用与模型名称不同的类作为示例)。
class SchoolSerializer
include FastJsonapi::ObjectSerializer
attributes :name, :description
belongs_to :classroom, serializer: ClassroomSerializer
end
答案 1 :(得分:0)
render json: SchoolSerializer.new(school, include: "classrooms.students")
区别在于渲染序列化程序时使用“ include”。这告诉序列化程序将键“ included”添加到返回的JSON对象中。
class SchoolSerializer
include FastJsonapi::ObjectSerializer
belongs_to :classroom
has_many :students, through: :classroom
attributes :school_name, :description
end
StudentSerializer
include FastJsonapi::ObjectSerializer
belongs_to :classroom
belongs_to :school
attributes :student_name
end
render json: SchoolSerializer.new(school).serialized_json
将返回一系列仅具有顶级标识符形式的学生
data: {
id: "123"
type: "school"
attributes: {
school_name: "Best school for Girls",
description: "Great school!"
...
},
relationships: {
students: [
{
id: "1234",
type: "student"
},
{
id: "5678",
type: "student"
}
]
}
}
include: "classroom.students"
将以以下形式返回全序列化学生记录:
data: {
id: "123"
type: "school"
attributes: {
school_name: "Best school for Girls"
...
},
relationships: {
classroom: {
data: {
id: "456",
type: "classroom"
}
},
students: [
{
data: {
id: "1234",
type: "student"
}
},
{
data: {
id: "5678",
type: "student"
}
}
]
},
included: {
students: {
data {
id: "1234",
type: "student",
attributes: {
student_name: "Ralph Wiggum",
...
},
relationships: {
school: {
id: "123",
type: "school"
},
classroom: {
id: "456",
type: "classroom"
}
}
},
data: {
id: "5678",
type: "student",
attributes: {
student_name: "Lisa Simpson",
...
},
relationships: {
school: {
id: "123",
type: "school"
},
classroom: {
id: "456",
type: "classroom"
}
}
}
},
classroom: {
// Effectively
// ClassroomSerializer.new(school.classroom).serialized_json
},
}
}