1

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.

Jarrett
  • 113
  • 1
  • 9

3 Answers3

7

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
smathy
  • 26,283
  • 5
  • 48
  • 68
  • +1 for reusability, brilliant clarity, extensibility, simplicity and efficiency. – Blake Taylor Apr 19 '11 at 14:10
  • I forgot to mention that employees belong to departments :through => :positions. Still applicable? – Jarrett Apr 19 '11 at 23:12
  • Hopefully you've tried it already and found out that yes, it works through a join table too. Time to accept my answer now, feed me ;) – smathy Apr 20 '11 at 19:02
0

If you don't need nil select options why you can't use .compact method?

@current_company.departments.collect {|d| [d.title, d.id] if d.employees.any?}.compact
Vasiliy Ermolovich
  • 24,459
  • 5
  • 79
  • 77
0

Or yet another way to do it...

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

The beauty of Ruby is there are so many ways to do anything ;)

Jim Morris
  • 2,870
  • 24
  • 15