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

推荐答案

参考 ActiveModel::Serializers::JSON#as_json 查看可以传递给 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" } ]
#    }

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

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

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

08-24 07:34