2012-04-02 98 views
13

我有三个型号:嵌套:JSON包括在Rails的

class A < ActiveRecord::Base 
    has_many :bs 
end 

class B < ActiveRecord::Base 
    has_one :c 
    belongs_to :a 
end 

class C < ActiveRecord::Base 
    belongs_to :b 
end 

我想获得一个包含所有B的和C的一个A. JSON数据我尝试了一些事情类似:

render json: @as, :include => [:bs => [:include=>[:c]] 

但没有用。这将是一个好方法。

回答

30

参考ActiveModel::Serializers::JSON#as_json看你可以传递给render :json的选项。引述:

要包括关联使用:include ......

第二级和高阶协会以及工作:

user.as_json(:include => { :posts => { 
          :include => { :comments => { 
              :only => :body } }, 
          :only => :title } }) 
# => { "id": 1, "name": "Konata Izumi", "age": 16, 
#  "created_at": "2006/08/01", "awesome": true, 
#  "posts": [ { "comments": [ { "body": "1st post!" }, { "body": "Second!" } ], 
#     "title": "Welcome to the weblog" }, 
#     { "comments": [ {"body": "Don't think too hard" } ], 
#     "title": "So I was thinking" } ] 
# } 

这是没有必要直接调用to_jsonas_json ,因为render :json会自动执行。

+1

如果您是滞留在轨道2,'呈现()'不支持':include',但'to_json()'支持。在这种情况下,调用'render:json => @ as.to_json(:include =>:bs)'是有意义的。 – 2014-10-17 18:11:52

+0

to_json有时会破坏嵌套struct – 2015-11-11 11:00:44

+0

@ Albert.Qing如果您遇到特定问题,应将其作为新问题发布。 – 2015-11-11 18:30:18

2

尝试

render :json => @as.to_json(:include => {:bs => :c}) 
5

您需要的哈希,而不是阵列通过

render :json => @as.to_json(:include => { :bs => {:include =>:c} }) 
0

试试这个:

render json: @as.to_json(include:{bs: {include:{c:}}}) 
0

试试这个:

render json: @tiquets, :include => { :enterprise => {:include => { :location => {:only => :lo_name } },:only => :en_name } } } 
+0

@OwaisKureshi代码唯一的答案可能不是一个好的,但它仍然是一个答案。我会推荐你​​这篇关于LQPRQ的文章:[你做错了:在低质量岗位队列中请求理智](http://meta.stackoverflow.com/questions/287563/youre-doing-it-在低质量岗位队列中的错误 - 理智的理由) – FelixSFD 2017-02-16 19:59:10

+0

@FelixSFD,我同意,但是应该有一些文字解释答案,或者他可以将其作为评论发布? – 2017-02-16 20:12:22

+0

@OwaisKureshi建议并最好稍微解释代码。但即使没有解释,这是一个答案。 – FelixSFD 2017-02-16 20:13:32