2017-04-22 2 views
0
나는 세 가지 모델, 항목 및 전송 및 카테고리 (일명 아이템 종류) 한

: 나는 결과레일 - has_many 관계를 포함

render json: @item, include: %i[transfer category] 
# FWIW the include doesn't seem to affect category at all... 

을 내 컨트롤러에서

class Item < ApplicationRecord 
    belongs_to :category 
    has_many :transfers 
end 

class Transfer < ApplicationRecord 
    belongs_to :item 
end 

class Category < ApplicationRecord 
    has_many :item 
end 

이 다음 모양을 취하는 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 배열에 포함되도록하려면 어떻게해야합니까?

감사합니다.

편집 : 복제하지 마세요. 응답을 중첩 시키려고하지 않고 JSON API 사양을 준수하기 위해 included 섹션에 포함 시켰습니다. 어쨌든, 나는 그것을 알아 냈고, 곧 답변이 곧 나올 것입니다!

+0

'transfer' 대신'transfers'를 사용해보십시오. – Gerry

+0

오타 고맙다 @ 게리. 결정된. 그래도 작동하지 않습니다 :/ –

+0

[중첩 : json include in 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, 포함 : {category : true, transfers : {include : : id}} 행운 없음 : / –

관련 문제