范围与协会.any?

时间:2011-04-18 18:38:03

标签: ruby-on-rails select tags scopes

我有两个模特,员工和部门。雇员通过职位属于部门。在select标签中,我只想列出其中有员工的部门。

现在我有:

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

这给我留下了几个零选择选项。我想我可以写一个像@ current_company.departments.with_employees那样有效的描述范围:

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

我意识到这不起作用,但我仍然坚持我应该做的事情。

3 个答案:

答案 0 :(得分:7)

请记住,连接是一个内连接,它正是您想要的 - 将连接写为范围...

scope :with_employees, :joins => :employees

答案 1 :(得分:0)

如果您不需要nil select选项,为什么不能使用.compact方法?

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

答案 2 :(得分:0)

或者另一种方法......

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

Ruby的美妙之处在于有很多方法可以做任何事情;)