我有一个Component
类,可以是Section
或Question
。 Section
可以有多个Component
(即Question
)。
我正在尝试让串行器发送回Component
(Section
)及其关联的Component
(Question
)。现在,根据下面的代码,我将获得与之关联的Question
和Section
对象(请参见下文)。如何让序列化器返回期望的结果?
响应(当前):
{"data":
[{"id": 1,
"type": "Section",
"content": "ABC",
"section_id": null,
"section": null
},
{"id": 2,
"type": "Question",
"content": "Q1",
"section_id": 1,
"section":
{"id": 1,
"type": "Section",
"content": "ABC",
"section_id": null
}
},
{"id": 3,
"type": "Question",
"content": "Q2",
"section_id": 1,
"section":
{"id": 1,
"type": "Section",
"content": "ABC",
"section_id": null
}
}]
}
响应(预期):
{"data":
[{"id": 1,
"type": "Section",
"content": "ABC",
"section_id": null,
"section":
{"id": 2,
"type": "Question",
"content": "Q1",
"section_id": 1
},
{"id": 3,
"type": "Question",
"content": "Q2",
"section_id": 1
}
}]
}
ComponentSerializer:
class ComponentSerializer < ActiveModel::Serializer
belongs_to :section
attributes :id,
:type,
:content,
:section_id
end
SectionSerializer:
class ComponentSerializer < ActiveModel::Serializer
has_many :components
attributes :id,
:type,
:content,
:section_id
end
component.rb(模型):
class Component < ApplicationRecord
# == Associations ==========================
belongs_to :project
belongs_to :section,
class_name: 'Section',
foreign_key: :section_id,
optional: true
end
section.rb(模型):
class Section < Component
# == Associations ==========================
has_many :components,
class_name: 'Component',
foreign_key: :component_id,
dependent: :destroy
end
component_controller.rb:
before_action :load_project
before_action :load_scope
def index
components = paginate @scope, per_page: per_page
data = ActiveModelSerializers::SerializableResource.new(
components,
each_serializer: ComponentSerializer
)
render_response(:ok, { data: data })
rescue ActiveRecord::RecordNotFound
render_response(:not_found, { resource: "Project/Lesson" })
end
def load_scope
@scope = @project.components
@scope = @scope.order("position")
end
def load_project
@project = Project.find(params[:project_id])
rescue ActiveRecord::RecordNotFound
render_response(:not_found, { resource: "Project/Lesson" })
end