我正在尝试在我的控制器中获取此查询。
select employer_id, count(*) from employees where termination_date is null group by employer_id order by employer_id;
employer_id | count
-------------+-------
1 | 592
2 | 2092
3 | 565
4 | 3589
7 | 4233
8 | 540
10 | 1035
11 | 3287
(8 rows)
我在控制器中有这个代码,我用for.each
得到了所有结果@employers = Employer.all.includes(:employees)
我只是尝试添加.where(... employees_date为null的员工)
<tbody>
<% @employers.each do |employer| %>
<tr>
<td><%= employer.name %></td>
# I want the result here
<td><%= employer.employees.size() %></td>
<td></td>
</tr>
<% end %>
</tbody>
答案 0 :(得分:1)
您可以将Arel where
添加到employees
集合。
employer.employees.where(termination_date: nil).size
注意,上面的代码将导致查询每一行,如
select count(*) from employees where employer_id = ? and termination_date is null
所以你结束了n + 1查询情况,如果你有很多行,这可能会有问题。
答案 1 :(得分:0)
你可以写成:
Employee.where(termination_date: nil)
.group(:employer_id)
.count
# => [{employer_id_1: count_1}, {employer_id_2: count_2}...]
更新:
如果您需要雇主姓名并计算每个雇主的雇员,您可以加入2个表:
@employers = Employee.joins(:employer)
.where(termination_date: nil)
.group("employers.name")
.count
为了测试查询,我创建了包含一些示例数据的相关表。表格数据如下:
[arup@app]$ rails db
SQLite version 3.7.17 2013-05-20 00:56:22
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .header on
sqlite> .mode column
sqlite> select * from employees;
id name created_at updated_at employer_id
---------- ---------- -------------------------- -------------------------- -----------
1 arup 2015-02-13 20:22:41.174700 2015-02-13 20:22:41.510749 2
2 arun 2015-02-13 20:22:41.362186 2015-02-13 20:22:41.513432 2
3 Joy 2015-02-13 20:23:27.533335 2015-02-13 20:23:27.677737 3
sqlite> select * from employers;
id name created_at updated_at
---------- ---------- -------------------------- --------------------------
2 ABC 2015-02-13 20:22:40.978798 2015-02-13 20:22:40.978798
3 XYZ 2015-02-13 20:23:27.086210 2015-02-13 20:23:27.086210
sqlite>
现在,我打开rails控制台,按照我的意愿得到每个雇主的雇员数量。请参阅rails控制台输出:
>> Employee.joins(:employer).where.not(name: nil).group("employers.name").count
(0.5ms) SELECT COUNT(*) AS count_all, employers.name AS employers_name FROM "employees" INNER JOIN "employers" ON "employers"."id" = "employees"."employer_id" WHERE ("employees"."name" IS NOT NULL) GROUP BY employers.name
=> {"ABC"=>2, "XYZ"=>1}
现在,您可以将您的观点写为:
<tbody>
<% @employers.each do |employer_name, employees_count| %>
<tr>
<td>
<%= employer_name %>
</td>
# I want the result here
<td>
<%= employees_count %>
</td>
<td></td>
</tr>
<% end %>
</tbody>