小编典典

嵌套:json包含在Rails中

json

我有三种模式:

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数据。我尝试了许多类似的操作:

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

但没有任何效果。什么是做到这一点的好方法。


阅读 293

收藏
2020-07-27

共1个答案

小编典典

请参阅以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

2020-07-27