Search code examples
ruby-on-railsselecttagsscopes

Scope with association .any?


I have two models, employees, and departments. Employes belong Departments through Positions. In a select tag I'd like to list only departments that have employees in them.

Right now I have:

@current_company.departments.collect {|d| [d.title, d.id] if d.employees.any?}

Which leaves me with a couple of nil select options. I thought I could write a scope for depmartments that would work like @current_company.departments.with_employees:

scope :with_employees, :where => (self.employees.any?)

I realize that won't work, but I'm stuck on what I should do.


Solution

  • Remember that a join is an inner join, which does precisely what you want - writing the join as a scope...

    scope :with_employees, :joins => :employees