简体   繁体   中英

Active record two level association and group by count

Consider the following association

Companies

has_many: departments

Departments

belongs_to: company
has_many: employees

Employees

belongs_to: department

Consider the following sample data

Companies

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

Departments

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

Employees

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

Is there a one liner in RoR to find the count of employees of a company, belongs to each grade? ie if company_id is equal to 1 then the output is as follows

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

A way I tried is to get departments for the company and then loop through it, fetch the grade grouped employee count for each department and add the counts. Is there any other way?

I think, I got a way.

Add another association in company using through to employees. So Company will become as follows

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

And then to find the count do as following.

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

Any other approach will be appreciated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM