嵌套 :json 包含在 Rails 中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9983436/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Nesting :json include in Rails
提问by Ibrahim Muhammad
I have three models:
我有三个模型:
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
I want to get json data containing all B's and C's for an A. I tried a number of things similar to:
我想获取包含 A 的所有 B 和 C 的 json 数据。我尝试了许多类似的事情:
render json: @as, :include => [:bs => [:include=>[:c]]
but nothing works. What would be a good way to do this.
但没有任何效果。这样做的好方法是什么。
回答by Jordan Running
Refer to ActiveModel::Serializers::JSON#as_jsonto see the options you can pass to render :json. To quote:
请参阅以ActiveModel::Serializers::JSON#as_json查看您可以传递给的选项render :json。报价:
To include associations use
: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" } ] # }
要包含关联,请使用
: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" } ] # }
It's not necessary to call to_jsonor as_jsondirectly, as render :jsondoes it automatically.
不需要调用to_json或as_json直接调用,因为render :json它会自动调用。
回答by Abid
You need to pass in hash instead of array
您需要传入哈希而不是数组
render :json => @as.to_json(:include => { :bs => {:include =>:c} })
回答by Frederick Cheung
Try
尝试
render :json => @as.to_json(:include => {:bs => :c})
回答by Kuberan
Try this:
尝试这个:
render json: @as.to_json(include:{bs: {include:{c:}}})
回答by Julian Botia
Try this:
尝试这个:
render json: @tiquets, :include => { :enterprise => {:include => { :location => {:only => :lo_name } },:only => :en_name } } }

