如何在活动记录查询下进行优化,使其不返回任何属于日期范围的记录

时间:2019-02-13 03:53:22

标签: ruby-on-rails query-optimization rails-activerecord

我想要一个优化的AR(ActiveRecord)查询,因为我当前的AR查询多次查询数据库

假设模型为巧克力,其列为 created_at 。 我的控制器中有以下AR查询:

for i in 1..4 
    @myHash[i] = Chocolate.where(created_at: (Time.now - i.hours)..(Time.now - (i-1).hours)).count    
end

上面的查询从数据库中检索了4次(假设当前时间是12:00)

Select COUNT(*) from Chocolate where created_at BETWEEN 11:00 AND 12:00
Select COUNT(*) from Chocolate where created_at BETWEEN 10:00 AND 11:00 
Select COUNT(*) from Chocolate where created_at BETWEEN 09:00 AND 10:00 
Select COUNT(*) from Chocolate where created_at BETWEEN 08:00 AND 09:00

如何更改查询,使其仅从数据库检索一次?

2 个答案:

答案 0 :(得分:1)

您可以使用如下查询:

Chocolate.where(Chocolate.arel_table[:created_at].gteq(4.hours.ago))
         .group("DATE_TRUNC('hour', created_at)")
         .count

它将返回一个哈希,其中记录的计数按小时分组。

{"2019-02-12 00:00:00"=>152, "2019-02-12 01:00:00"=>57, "2019-02-12 02:00:00"=>132, "2019-02-12 03:00:00"=>132}

希望这会有所帮助。

答案 1 :(得分:0)

尝试纯字符串条件:

Chocolate.where('created_at BETWEEN ? AND ?', (Time.now - i.hours), (Time.now - (i-1).hours))