我有一个Department
与用户有两个关联的模型,这样
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