范围与协会.any?

Jar*_*ett 1 tags select ruby-on-rails scopes

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

现在我有:

@current_company.departments.collect {|d| [d.title, d.id] if d.employees.any?}
Run Code Online (Sandbox Code Playgroud)

这给我留下了几个零选择选项.我以为我可以编写像@ current_company.departments.with_employees那样工作的depmartments的范围:

scope :with_employees, :where => (self.employees.any?)
Run Code Online (Sandbox Code Playgroud)

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

sma*_*thy 7

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

scope :with_employees, :joins => :employees
Run Code Online (Sandbox Code Playgroud)