【发布时间】:2017-09-19 15:07:53
【问题描述】:
我有三个模型,Item and Transfer 和 Category(又名 Item Type):
class Item < ApplicationRecord
belongs_to :category
has_many :transfers
end
class Transfer < ApplicationRecord
belongs_to :item
end
class Category < ApplicationRecord
has_many :item
end
在我的控制器中,我有
render json: @item, include: %i[transfer category]
# FWIW the include doesn't seem to affect category at all...
这会产生一个 JSON Api 有效负载,其形状如下:
{
data: {
id,
attributes: {
/* the other attributes */
transfers: [ { /* full transfer object */ } ]
},
relationships: {
category: { data: { id, type: 'categories' } },
transfers: { data: [ { /* full transfer object */ } ]
}
}
},
included: [ { type: 'category', id, attributes } ]
}
这些类别的行为符合我的预期。如何让每个 transfer 包含在 included 数组中,而不是嵌套在属性或关系中?
谢谢!
编辑:不是重复的。我没有尝试嵌套响应,只是将它们包含在 included 部分中以符合 JSON API 规范。无论如何,我想通了,很快就会有答案!
【问题讨论】:
-
尝试使用
transfers而不是transfer。 -
感谢@Gerry,这是一个错字。固定的。虽然仍然不起作用:/
标签: ruby-on-rails include has-many json-api