Rails 3 activerecord kids children write

My models:

class Person has_many :projects class Project belongs_to :person has_many :tasks class Task belongs_to :project 

Given an instance of person , person = Person.find(10) , is there an easy way to access all tasks that belong to all projects for person ? In addition, I will need to additionally filter the results of projects if projects.duration < x days . I could try manually building the result set of person.projects and then person.projects through each project to get the related tasks , but I hope there is another simpler, more elegant syntax that I don't know about. BTW, person.projects.tasks does not work.

+4
source share
1 answer

Yes, there is a more elegant way to do this. You can look forward to downloading the results. Let me show you.

without filtering the list of faces

 person = Person.find(10).includes(:projects=>:tasks) 

This will load the results, so if you call person.projects.first.tasks.first , it has already been downloaded, and more sql queries will fail.

If you want to filter them out, follow these steps:

 person = Person.where('people.id=10 AND projects.duration < ?', x).includes(:projects=>:tasks) 

If you want to iterate over only all tasks without iterating over projects, you should establish a relationship such as:

 class Person has_many :projects has_many :tasks, :through=>:projects end 

To repeat them, do the following:

 person = Person.find(10) person.tasks.where('projects.duration < ?', x) 
+9
source

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


All Articles