嵌套:json包含在Rails中 [英] Nesting :json include in Rails

查看:65
本文介绍了嵌套: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

我想获取包含A的所有B和C的json数据.我尝试了许多类似的事情:

I want to get json data containing all B's and C's for an A. I tried a number of things similar to:

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

但没有任何效果.这样做的好方法是什么.

but nothing works. What would be a good way to do this.

推荐答案

请参阅 ,查看可以传递给render :json的选项.去引用:

Refer to ActiveModel::Serializers::JSON#as_json to see the options you can pass to render :json. To quote:

要包含关联,请使用:include ...

第二级和更高级别的关联也可以工作:

Second level and higher order associations work as well:

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" } ]
#    }

不必像render :json那样自动调用to_jsonas_json.

It's not necessary to call to_json or as_json directly, as render :json does it automatically.

这篇关于嵌套:json包含在Rails中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆