Ibrahim Muhammad
Ibrahim Muhammad

Reputation: 2896

Nesting :json include in Rails

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 < ActiveRecord::Base
  belongs_to :b
end

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.

Upvotes: 27

Views: 29923

Answers (6)

xeitor
xeitor

Reputation: 377

For those looking to do the same thing but with ruby's new syntax instead, it would be something like this

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

And to extract only some attributes:

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

Upvotes: 6

Julian Botia
Julian Botia

Reputation: 1951

Try this:

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

Upvotes: 2

Abid
Abid

Reputation: 7227

You need to pass in hash instead of array

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

Upvotes: 9

Jordan Running
Jordan Running

Reputation: 106027

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.

Upvotes: 51

Kuberan
Kuberan

Reputation: 141

Try this:

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

Upvotes: 0

Frederick Cheung
Frederick Cheung

Reputation: 84114

Try

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

Upvotes: 2

Related Questions