我有一个现有的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进行此查询吗?
答案 0 :(得分: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')
答案 1 :(得分:1)
您可以像这样简化where子句:
date_range = Date.today.beginning_of_year..Date.today.monday
Timesheet.where(:week_starting => date_range).
这将成为BETWEEN
条款。