简体   繁体   English

Rails从两个表中的关联加入

[英]Rails join from association in two tables

I have to tables: Associates and Departments 我要表格:部门和部门

One associate belongs to a department (belongs_to) and one department has many associates (has_many) 一个部门属于一个部门(属于),一个部门具有许多部门(has_many)

What I', trying to do is count number of associates on each department and make a pie chart with the data, i got the chart working with something basic (Department.count) 我想做的是计算每个部门的员工人数,并用数据制作一个饼图,我得到了处理基本情况的图表(Department.count)

I just started with rails and I'm having issues with the query 我刚开始使用Rails,但查询出现问题

Associate.joins(:department).group(:name).count

what i get is the following 我得到的是以下

Mysql2::Error: Column 'name' in field list is ambiguous: SELECT COUNT(*) AS count_all, name AS name FROM associates INNER JOIN departments ON departments . Mysql2 :: Error:字段列表中的列“名称”不明确:SELECT COUNT(*)AS count_all,名称AS名称FROM associates INNER JOIN departments ON departments id = associates . id = associates department_id GROUP BY name department_id GROUP BY名称

I tried doing a select, find and I just cant seem to get it right 我尝试进行选择,查找,但似乎做对了

If you have your associations setup correctly, I believe you should be able to do something like this: 如果您正确设置了关联,我相信您应该可以执行以下操作:

Department.find(<some_id>).associates.count

Or if you have all the departments, and you're looping through them, let's say in a view and you want to get all the counts, you can do something like this: 或者,如果您拥有所有部门,并且正在遍历这些部门,那么可以在一个视图中说,如果您想获取所有计数,则可以执行以下操作:

@departments = Deparment.all

@departments.each do |department|
  department.associates.count
end

You're associate table will need a department_id column on it. 您要关联的表上将需要一个department_id列。

As stated in the comment on your post, you have to resolve the ambiguous name attributed by specifying the table. 如帖子评论中所述,您必须通过指定表格来解决属性name不明确的问题。 You can do so either with the string as suggested, or by passing a block to group_by : 您可以按照建议的字符串进行操作,也可以将一个块传递给group_by

Associate.joins(:department).group_by(&:name).count

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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