活动记录两级关联和按组计数

时间:2014-05-20 11:26:26

标签: mysql ruby-on-rails activerecord

考虑以下关联

公司

has_many: departments

部门

belongs_to: company
has_many: employees

员工

belongs_to: department

考虑以下样本数据

公司

+------------+--------------+
| company_id | company_name |
+------------+--------------+
|          1 | Company A    |
|          2 | Company B    |
+------------+--------------+

部门

+---------------+------------+-----------------+
| department_id | company_id | department_name |
+---------------+------------+-----------------+
|             1 |          1 | Administration  |
|             2 |          1 | Development     |
|             3 |          1 | Designing       |
+---------------+------------+-----------------+

员工

+-------------+---------------+---------------+----------------+
| employee_id | department_id | employee_name | employee_grade |
+-------------+---------------+---------------+----------------+
|           1 |             1 | EmpA          | grade1         |
|           2 |             1 | EmpB          | grade1         |
|           3 |             2 | EmpC          | grade1         |
|           4 |             2 | EmpD          | grade2         |
+-------------+---------------+---------------+----------------+

RoR中是否有一个班轮来查找公司员工的数量,属于每个等级?即如果company_id等于1,则输出如下

+--------+-------+
| grade  | count |
+--------+-------+
| grade1 |     3 |
| grade2 |     1 |
+--------+-------+

我尝试的方法是获取公司的部门,然后循环访问它,获取每个部门的成绩分组员工数并添加计数。还有其他办法吗?

1 个答案:

答案 0 :(得分:0)

我想,我有办法。

使用through向员工添加公司中的另一个关联。所以公司将如下

has_many :departments
has_many :employees, :through => :departments

然后找到计数如下。

Company.find([company_id]).employees.group('employee_grade').count

任何其他方法都将受到赞赏。