2017-04-22 107 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}} 没有运气:/ –