Rails按关联计数和相同模型上的关联字段排序

时间:2012-12-03 21:21:19

标签: ruby-on-rails activerecord

我有一个Department模型,其中有两个与User的关联,以便

class Department < ActiveRecord::Base
   has_many :members, class_name:"User", foreign_key:"department_id"
   belongs_to :director, class_name:"User", foreign_key:"director_id
end

要在列表中显示此模型,按成员数量排序,我可以执行此操作

@departments = Department.select("departments.*, COUNT(users.id) AS members").joins(:members).group("departments.id")
@departments = @departments.order("members ASC")

如果我想按导演相关模型中的字段(last_name)排序,我可以这样做:

@departments = Department.includes(:director)
@departments = @departments.order("users.last_name")

但是,我无法将这两个查询组合成一个允许对两者进行正确排序的查询。如果我做

Department.select("departments.*, COUNT(users.id) AS members").joins(:members, :director).group("departments.id, users.last_name")

然后我得到了大量的重复结果,我也排除了director_id为零的结果。如何构建查询以便我可以COUNT(users.id)director.last_name订购?

修改:这是该错误合并查询的.to_sql

SELECT departments.*, COUNT(users.id) AS members FROM "departments" 
INNER JOIN "users" ON "users"."department_id" = "departments"."id" 
INNER JOIN "users" "directors_departments"    
ON "directors_departments"."id" = "departments"."director_id" 
GROUP BY departments.id, users.last_name 
ORDER BY users.last_name DESC

1 个答案:

答案 0 :(得分:4)

所以这里有两个问题:

  1. 您在可能不存在的.joins关联上使用belongs_to
  2. 您正在加入相同的用户表两次(对于2个不同的关联),导致rails生成表别名,以便SQL有效。但是你没有对这个别名进行分组。
  3. 解决方案:

    你需要一个LEFT JOIN,遗憾的是它并不像标准连接那么漂亮。您还需要修改.group子句:

    Department.
      select("departments.*, COUNT(users.id) AS members").
      joins(:members, "LEFT JOIN users directors ON departments.director_id = directors.id").
      group("departments.id, directors.last_name").
      order("members, directors.last_name")