如何让Rails的Through关联渲染为其所属关联的子层级
Rails调整序列化输出的关联嵌套结构
第一步:修正模型关联的错误写法
你的Review模型里otherpics的关联写了两个through,不符合Rails语法规范,先修正关联定义:
class Review < ApplicationRecord has_one :gamesection has_many :releases, through: :gamesection has_one :cover, through: :gamesection has_many :otherpics, through: :cover end
(注:需确保Gamesection模型定义了has_one :cover,Cover模型定义了has_many :otherpics,关联才能正常工作)
第二步:修改序列化器配置
序列化器的结构决定最终输出的嵌套层级,你需要把releases、cover、otherpics从Review的直接关联移到Gamesection的序列化器中,以下分两种常用序列化器说明:
若使用ActiveModel::Serializers
- 定义
GamesectionSerializer,包含需要嵌套的关联:
class GamesectionSerializer < ActiveModel::Serializer # 添加上你需要展示的Gamesection属性 attributes :id, :name has_many :releases has_one :cover has_many :otherpics end
- 修改
ReviewSerializer,只关联gamesection并指定使用上面的序列化器:
class ReviewSerializer < ActiveModel::Serializer # 添加上你需要展示的Review属性 attributes :id, :content has_one :gamesection, serializer: GamesectionSerializer end
若使用FastJSONAPI
- 定义
GamesectionSerializer:
class GamesectionSerializer include FastJsonapi::ObjectSerializer # 添加上你需要展示的Gamesection属性 attributes :id, :name has_many :releases has_one :cover has_many :otherpics end
- 修改
ReviewSerializer:
class ReviewSerializer include FastJsonapi::ObjectSerializer # 添加上你需要展示的Review属性 attributes :id, :content has_one :gamesection, serializer: GamesectionSerializer end
配置完成后,序列化输出的结构就会变成你期望的层级:
Review ->gamesection --->release --->cover --->otherpics
内容的提问来源于stack exchange,提问作者Dan Seminara
相关产品推荐
相关产品推荐

