我有一个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
答案 0 :(得分:4)
所以这里有两个问题:
.joins
关联上使用belongs_to
。解决方案:
你需要一个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")