Rails - 如何订购sum()和group()的查询?

时间:2015-05-13 17:42:53

标签: ruby-on-rails ruby-on-rails-4

在我们的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()订购查询的正确方法是什么?

1 个答案:

答案 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 }