[英]Active Model Serializers has_many associations
I'm using the gem active_model_serializers
. 我正在使用gem
active_model_serializers
。
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
Controller: 控制器:
def index
@project_groups = ProjectGroup.all.includes(:projects)
render json: @project_groups, include: 'projects'
end
I'm getting the following response : 我收到以下回应 :
{
"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"
}
}
}
}
]
}
I want to retrieve the associations inside the relationships object , not outside (in included
array
) as in the response that I'm receiving. 我想检索关系 对象内部的关联 ,而不是像接收到的响应那样在外部 (
included
array
)检索关联。 Is it possible? 可能吗?
PS1: belongs_to associations works fine, the associations comes inside the relationships object , as in docs. PS1: belongs_to关联可以正常工作,该关联位于Relationships 对象内部,如docs中所示。
PS2: I want to do this because I have 3 or 4 associations and I want to access them from each object. PS2:之所以要这样做,是因为我有3个或4个关联,并且希望从每个对象访问它们。 This way that I'm getting the response will be a real mess.
这样,我得到的答复将是一团糟。
You can do this by defining projects manually like this. 您可以通过这样手动定义项目来实现。
class ProjectGroupSerializer < ActiveModel::Serializer
attributes :id, :name, :description, :projects
def projects
object.projects.map do |project|
::ProjectSerializer.new(project).attributes
end
end
end 结束
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.