Skip to content

Instantly share code, notes, and snippets.

@kagemusha
Created December 31, 2011 02:14
Show Gist options
  • Save kagemusha/1542498 to your computer and use it in GitHub Desktop.
Save kagemusha/1542498 to your computer and use it in GitHub Desktop.
Rails include related Model in JSON Response
Tested on: Rails 3.1
In this example, you want to return as json a group of Items and the name of the Company which makes them.
Models are as follows:
class Company < ActiveRecord::Base
has_many :items
class Item < ActiveRecord::Base
belongs_to :company
In your controller, do something like this:
def index
@items = Item.find :all, :include => :company #reduce # of queries
respond_to do |format|
format.json { render json: @items.as_json(:include=>{:company=>{:only=>:name}}) }
end
end
Ref: http://stackoverflow.com/questions/8302715/rails-eager-loading-as-json-includes
@tkivite
Copy link

tkivite commented Sep 18, 2020

Thanks. It works

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment