Trip
Trip

Reputation: 27114

Rails - How do I pull in associated model data into a controller json call?

I have two models that are associated with each other.

Customer has_one :primary_contact

And I would like to pull this data out in a json object so that the primary_contact model is associated with the Customer object.

Right now my controller does this :

@customers = current_account.customers.all

respond_to do |format|
  format.json { render :json => @customers.to_json, :layout => false }
end

But I woud like to also include in these customer objects, their primary contact info as well. How would I go about pulling this information in a associated context so that I get this data in jQuery as :

value.primary_contact.name

Right now, I can pull the json out for the customer object with this :

value.name
value.address

Upvotes: 2

Views: 193

Answers (2)

Syed Aslam
Syed Aslam

Reputation: 8807

To include associations, use :include.

@customers = current_account.customers.all(:include => :primary_contact)

respond_to do |format|
  format.json { render :json => @customers.to_json, :layout => false }
end

Upvotes: 1

Jordan Running
Jordan Running

Reputation: 106027

Per the documentation, use the :include option:

To include associations, use :include.

konata.to_json(:include => :posts)
# => {"id": 1, "name": "Konata Izumi", "age": 16,
#     "created_at": "2006/08/01", "awesome": true,
#     "posts": [{"id": 1, "author_id": 1, "title": "Welcome to the weblog"},
#               {"id": 2, author_id: 1, "title": "So I was thinking"}]}

Upvotes: 3

Related Questions