2017-04-22 33 views
0

我有三個型號,項目轉讓和類別(又名項目類型):導軌和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規範。無論如何,我明白了,一個答案即將到來!

+0

嘗試使用'transfers'而不是'transfer'。 – Gerry

+0

謝謝@Gerry,這是一個錯字。固定。仍然不工作,雖然:/ –

+0

[嵌套:json包括在Rails]可能的重複(http://stackoverflow.com/questions/9983436/nesting-json-include-in-rails) – TiSer

回答

0

原來我錯過了TransferSerializer!一旦我添加了一個,它就像你期望的那樣放入included陣列中。

1

我認爲,這個問題有點重複。檢查了這一點:Nesting :json include in Rails

您需要使用as_json和嵌套include

+0

我試過各種形式 render json:@item,include:{category:true,transfers:{include::id}} 沒有運氣:/ –