【发布时间】:2017-02-03 03:36:57
【问题描述】:
我正在使用 gem active_model_serializers。
序列化器:
class ProjectGroupSerializer < ActiveModel::Serializer
attributes :id, :name, :description
has_many :projects
end
class ProjectSerializer < ActiveModel::Serializer
attributes :id, :name, :description
belongs_to :project_group
end
控制器:
def index
@project_groups = ProjectGroup.all.includes(:projects)
render json: @project_groups, include: 'projects'
end
我收到以下回复:
{
"data": [
{
"id": "35",
"type": "project_groups",
"attributes": {
"name": "sdsdf",
"description": null
},
"relationships": {
"projects": {
"data": [
{
"id": "1",
"type": "projects"
},
{
"id": "2",
"type": "projects"
}
]
}
}
}
],
"included": [
{
"id": "1",
"type": "projects",
"attributes": {
"name": "qweqwe",
"description": null,
"project_group_id": 1
},
"relationships": {
"project_group": {
"data": {
"id": "1",
"type": "project_groups"
}
}
}
},
{
"id": "2",
"type": "projects",
"attributes": {
"name": "ewe",
"description": null,
"project_group_id": 2
},
"relationships": {
"project_group": {
"data": {
"id": "2",
"type": "project_groups"
}
}
}
}
]
}
我想检索 relationships object 内部的关联,而不是 外部(在 includedarray 中),如响应我收到的。有可能吗?
PS1:belongs_to 关联工作正常,关联位于 relationships object 中,就像在文档中一样。
PS2:我想这样做是因为我有 3 或 4 个关联,并且我想从每个对象访问它们。这样我得到回复的方式将是一团糟。
【问题讨论】:
-
顺便说一句:这将是无效的 JSON:API,因此不太可能易于维护/支持。关系键应该包含resource identifier objects。如果您将它们保留为有效的 JSON:API,则 JSON:API 客户端应该为您解析它们(但我同意,如果编写自己的客户端,解析会有点麻烦)
标签: ruby-on-rails activemodel active-model-serializers