Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails to_json include multiple belongs_to and has_many references

I have the following Model structure:

class Server < ActiveRecord::Base
  has_many :websites
end

class Website < ActiveRecord::Base
  belongs_to :server
  has_many :plugins
end

class Plugin < ActiveRecord::Base
  belongs_to :website
end

When I call server/1.json I only get the JSON of the Server attributes. What I want is to include all its websites and the websites to include all their plugins. How would I achieve this?

format.json { render :json => @server.to_json(:include => :websites) }

This works for including the websites but I want to include the references inside the websites too.

like image 583
tolgap Avatar asked Nov 03 '25 02:11

tolgap


1 Answers

What you want is

format.json { render json: @server.to_json(include: {websites: {include: :plugins}}) }

You can pass in a hash to include as opposed to an array and in doing so specify nested includes.

like image 175
Leo Correa Avatar answered Nov 06 '25 00:11

Leo Correa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!