我有三個型號,項目轉讓和類別(又名項目類型):導軌和JSON API - 包括的has_many關係
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
謝謝@Gerry,這是一個錯字。固定。仍然不工作,雖然:/ –
[嵌套:json包括在Rails]可能的重複(http://stackoverflow.com/questions/9983436/nesting-json-include-in-rails) – TiSer