sqlruby-on-railsrubyhas-manyfind-by-sql

Rails find_by in a lower hierarchy level


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?

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