Reputation: 21536
I've got a rails3 app with the following structure
Users has_many :tasks has_many :staff has_many :managers Tasks has_one :location Locations has_many :staff has_one :manager Staff belongs_to :users belongs_to :location Managers belongs_to :users belongs_to :location
Now in my json output, I'm trying to get a the User, their tasks, each task location, and the locations staff and manager.
I've got
@User = User.find(params[:id], :include{:tasks=>:location})
This outputs the user and locations of the tasks, but not the tasks themselves.
And any further includes I attempt to add, result in an error for example
@User = User.find(params[:id], :include{:tasks=>:location=>:staff})
I get an error of "unexpected tASSOC, expecting }.
What is the correct way to write this so I get all the associated data for this user?
Upvotes: 4
Views: 1303
Reputation: 34350
You should be able to get the user and associated objects using this command:
@user = User.includes(:tasks => {:location => :staff}).find(params[:id])
You'll see a few queries execute. The first will retrieve the user, the second the related tasks, the third the related locations and the fourth the related staff. You'll notice that no queries execute when you type any of the following:
@user.tasks.first.location.staff
@user.tasks.first.location
@user.tasks.first
Upvotes: 4