【发布时间】:2019-03-19 04:18:48
【问题描述】:
在使用 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
【问题讨论】:
-
请用“学校”模型协会更新问题。
-
@OleksiiBaidan 我更新了模型详细信息。
-
事实上,您可以将关联添加到您的序列化程序。 [文档] (github.com/Netflix/fast_jsonapi#serializer-definition)。当您在 School 序列化程序中设置 has_many: 教室时,rails 将尝试查找定义的 ClassroomSerializer 类并使用它进行渲染。因此,在您的序列化程序文件夹中创建 classtoom_serializer.rb。
标签: ruby-on-rails ruby fastjsonapi