Question

I have the following models:

Company has_many Employees has_many Projects

Projects have a deadline:dateTime

Now I want, with a statement that generates a single SQL, to get the next deadline from any project of a given company.

i.e.

def get_next_deadline
   * * * select deadline from projects where employee_id in (employees.each |i| )) * * *
end

What I don't want is to iterate over all the companies Employees and check for the next deadline, accessing the DB once for each Employee.

Is there a more elegant find command than

find_by_sql?
Was it helpful?

Solution

if you add

has_many :projects, :through => :employees

to your company model, then you can do

some_company.projects.order('deadline').first

to find the project with the first deadline for that company

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top