我想要一个优化的AR(ActiveRecord)查询,因为我当前的AR查询多次查询数据库
假设一个带有created_at列的Model Chocolate。我的控制器中有以下AR查询:
for i in 1..4
@myHash[i] = Chocolate.where(created_at: (Time.now - i.hours)..(Time.now - (i-1).hours)).count
end
上面的查询从db中检索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
如何更改查询以便它只从db检索一次?
你可以使用这样的查询:
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}
希望这可以帮助。
尝试纯字符串条件:
Chocolate.where('created_at BETWEEN ? AND ?', (Time.now - i.hours), (Time.now - (i-1).hours))