嵌套:json包含在Rails中

Ibr*_*mad 16 json ruby-on-rails-3

我有三个型号:

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
Run Code Online (Sandbox Code Playgroud)

我想得到包含所有B和C的json数据用于A.我尝试了许多类似的东西:

render json: @as, :include => [:bs => [:include=>[:c]]
Run Code Online (Sandbox Code Playgroud)

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

Jor*_*ing 35

请参阅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" } ]
#    }
Run Code Online (Sandbox Code Playgroud)

没有必要直接打电话to_jsonas_json直接打电话render :json.

  • 如果你被 Rails 2 困住了,`render()` 不支持 `:include`,但是 `to_json()` 支持。在这种情况下,调用`render :json =&gt; @as.to_json(:include =&gt; :bs)` 是有意义的。 (2认同)

Abi*_*bid 7

您需要传入哈希而不是数组

render :json => @as.to_json(:include => { :bs => {:include =>:c} })
Run Code Online (Sandbox Code Playgroud)


小智 6

对于那些想要做同样的事情但使用 ruby​​ 的新语法的人来说,它会是这样的

render json: @as.to_json(include: { bs: { include: :c}})
Run Code Online (Sandbox Code Playgroud)

并仅提取一些属性:

render json: @a.to_json(only: [:name, :phone, :phone_mobile], include: { bs: { only: :email, include: {c: {only: [:id, :name]}}}})
Run Code Online (Sandbox Code Playgroud)