Output deeply nested json associations

I have a rails3 application 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 release I am trying to get the User, their tasks, the location of each task, as well as the staff and the location manager.

I have

  @User = User.find (params [: id],: include {: tasks =>: location})

This displays the user and the location of the tasks, but not the tasks themselves.

And in the future I try to add, for example, leads to an error

  @User = User.find (params [: id],: include {: tasks =>: location =>: staff})

I get the error "unexpected tASSOC pending".

What is the correct way to write, so I get all related data for this user?

+4
source share
1 answer

You can get the user and related objects with this command:

@user = User.includes(:tasks => {:location => :staff}).find(params[:id]) 

You will see a few requests. The first will retrieve the user, the second will be related tasks, the third will be the corresponding locations, and the fourth will be the appropriate personnel. You will notice that no queries are executed when you enter any of the following values:

 @user.tasks.first.location.staff @user.tasks.first.location @user.tasks.first 
+4
source

Source: https://habr.com/ru/post/1341351/


All Articles