在使用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发布于 2018-10-14 17:53:03
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然后将其直接包含在学校序列化程序中。
更新:还请注意,您可以直接指向所需的序列化程序类。(如果您想使用与模型名称不同的类作为示例)。
class SchoolSerializer
include FastJsonapi::ObjectSerializer
attributes :name, :description
belongs_to :classroom, serializer: ClassroomSerializer
end发布于 2019-12-11 03:21:25
render json: SchoolSerializer.new(school, include: "classrooms.students")
不同之处在于在呈现序列化程序时使用"include“。这告诉序列化程序向返回的JSON对象添加一个“包含”键。
class SchoolSerializer
include FastJsonapi::ObjectSerializer
belongs_to :classroom
has_many :students, through: :classroom
attributes :school_name, :description
endStudentSerializer
include FastJsonapi::ObjectSerializer
belongs_to :classroom
belongs_to :school
attributes :student_name
endrender 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
},
}
}https://stackoverflow.com/questions/52804847
复制相似问题