Nesting :json include in Rails

前端 未结 5 1723
悲哀的现实
悲哀的现实 2020-12-10 02:37

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 < Activ         


        
相关标签:
5条回答
  • 2020-12-10 02:55

    Try this:

    render json: @as.to_json(include:{bs: {include:{c:}}})
    
    0 讨论(0)
  • 2020-12-10 02:58

    You need to pass in hash instead of array

    render :json => @as.to_json(:include => { :bs => {:include =>:c} })
    
    0 讨论(0)
  • 2020-12-10 02:59

    Try this:

    render json: @tiquets, :include => { :enterprise => {:include => { :location => {:only => :lo_name } },:only => :en_name } } }
    
    0 讨论(0)
  • 2020-12-10 03:07

    Refer to ActiveModel::Serializers::JSON#as_json to see the options you can pass to render :json. To quote:

    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" } ]
    #    }
    

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

    0 讨论(0)
  • 2020-12-10 03:12

    Try

    render :json => @as.to_json(:include => {:bs => :c})
    
    0 讨论(0)
提交回复
热议问题