嵌套:json包含在Rails中

时间:2012-04-02 20:35:00

标签: ruby-on-rails-3 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

我想获得包含所有B和C的json数据。我尝试了许多类似的东西:

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

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

6 个答案:

答案 0 :(得分:33)

请参阅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自动执行此操作。

答案 1 :(得分:7)

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

render :json => @as.to_json(:include => { :bs => {:include =>:c} })

答案 2 :(得分:2)

尝试

render :json => @as.to_json(:include => {:bs => :c})

答案 3 :(得分:0)

试试这个:

render json: @as.to_json(include:{bs: {include:{c:}}})

答案 4 :(得分:0)

试试这个:

render json: @tiquets, :include => { :enterprise => {:include => { :location => {:only => :lo_name } },:only => :en_name } } }

答案 5 :(得分:0)

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

render json: @as.to_json(include: { bs: { include: :c}})

并且只提取一些属性:

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