在我们的Rails 4.2应用中,这是查询sum()
和group()
payment
记录:
Payment.joins(:project, :pr_category).select("sum(payments.amount) as Total, projects.name as Project, definitions.name as Category").group('payments.project_id, payments.pr_category_id').order('payments.project_id')
查询根据项目及其类别完成作业创建总和。但是我们很难order it by project_id
(一个项目的记录分散)。我们还尝试order('Project')
无效(我们没有尝试添加project_id
作为列,并尝试对其进行排序,因为我们不需要id)。还试图在order
之后立即joins
。所有这些都无法改变查询的顺序。从sum()
和group()
订购查询的正确方法是什么?
答案 0 :(得分:2)
您可以使用sort_by
mixins的Enumerable
在ActiveRecord之外排序:
Payment.joins(:project, :pr_category).select("sum(payments.amount) as Total, projects.name as Project, definitions.name as Category, payments.project_id as project_id").group('payments.project_id, payments.pr_category_id').sort_by { |p| c.project_id }