2017-04-22 13 views
0

私は三つのモデル、アイテムと転送とカテゴリ(別名アイテムタイプ)があります。私のコントローラでRailsの - に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... 

を持っています

{ 
    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 } ] 
} 

JSON Apiペイロードは、次のような形を取っています。それぞれのtransferが属性または関係にネストされているのではなく、included配列に含まれるようにするにはどうすればよいですか?

ありがとうございました!

編集:重複しません。回答を入れ子にするつもりはなく、JSON API仕様に準拠するためにはincludedセクションに含めてください。とにかく、私はそれを理解したので、すぐに答えが出ます!

+0

'transfer'の代わりに' transfers'を試してみてください。 – Gerry

+0

ありがとう@Gerryはタイプミスでした。一定。それでもまだ動作しません:/ –

+0

[ネスト:jsonインクルードの可能な複製](http://stackoverflow.com/questions/9983436/nesting-json-include-in-rails) – TiSer

答えて

0

私には見つからなかったTransferSerializer!一度追加したら、期待通りにincluded配列に配置されました。

1

私はこの質問はちょっと重複していると思います。これをチェックしてください:Nesting :json include in Rails

as_jsonとネストしたincludeを使用する必要があります。

+0

私は様々な形式を試みました レンダリングjson:@item、include:{カテゴリ:true、transfers:{インクルード::id}} 運がない/ –

関連する問題