首页 > 解决方案 > 序列化为 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

标签: ruby-on-railsrubyfastjsonapi

解决方案


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

推荐阅读