bra*_*rad 7 activerecord ruby-on-rails
For the situation where Employee has_many Clients, I am trying to write an ActiveRecord query that will return all of the Employees that have n or more clients. It's simple enough to write a join query to find all of the Employees with at least 1 client but extending my query to this more general case has left me stumped.
Edit - I should add that I'm trying to do this entirely at the database level. I want to avoid iterating over the collection in Ruby.
bra*_*rad 18
感谢mu和vijikumar,这就是我想出来的
Employee.select("employees.*").joins(:clients).group("employees.id").having("count(clients.id) > ?", n)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3461 次 |
| 最近记录: |