Created
December 31, 2011 02:14
-
-
Save kagemusha/1542498 to your computer and use it in GitHub Desktop.
Rails include related Model in JSON Response
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks. It works