2

我有一个现有的 Rails 2.3.x 应用程序,它使用以下代码块来总结给定数据范围的 4 列数据。

results = connection.execute(<<-SQL)
  SELECT sum(total_hours), sum(expected_hours), sum(total_billable), sum(expected_billable)
  FROM `timesheets`
  WHERE (`timesheets`.`week_starting` BETWEEN '#{Date.today.beginning_of_year}' AND '#{Date.today.monday}')
SQL
total_hours, expected_hours, total_billable, expected_billable = results.fetch_row.map(&:to_f).map(&:to_d)

当我升级到 Rails 3 和 mysql2 时,fetch_row 方法不再存在,所以我认为这是使用 ARel 整理此查询的好机会。

有谁知道如何使用 ARel 进行此查询?

4

2 回答 2

4

以模块化“构建器”风格编写,允许重构为可重用范围:

Timesheet.where('week_starting >= ?', Date.today.beginning_of_year).
  where('week_starting < ?', Date.today.monday).
  select('SUM(total_hours) as total_hours').
  select('SUM(expected_hours) as expected_hours').
  select('SUM(total_billable) as total_billable').
  select('SUM(total_hours) as expected_billable')
于 2012-04-13T03:04:21.800 回答
1

您可以像这样简化 where 子句:

date_range = Date.today.beginning_of_year..Date.today.monday
Timesheet.where(:week_starting => date_range).

这变成了一个BETWEEN子句。

于 2012-04-13T04:10:39.010 回答