ruby-on-rails - 序列化为 json 时如何包含子关联?
问题描述
在使用 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
解决方案
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
推荐阅读
- react-native - React Native 从图像中读取 pdf417 条码
- android - 来自 gradle.properties 的 Android manifestPlaceholders
- php - Mongodb如何更新多个数组文件
- python - 在不占用键盘的情况下将击键发送到非活动的 GUI 应用程序
- python - 如何重命名然后将特定子文件夹移动到另一个目录?
- python - 在python中返回一个元组的文字字符串
- c# - AvalonDock MVVM 锚定位置
- javascript - Angular 5 +如何使用IE 11中的键盘左/右选项逐个字符移动光标
- python - 将包含零的列导出到 csv
- javascript - 如何自定义fabricjs画布坐标系?