按日期计算记录,返回零值

时间:2013-10-15 13:40:18

标签: ruby-on-rails

我试图找到一种方法来输出两个给定日期之间每天的记录数量:

from = 7.days.ago.to_date
to = Date.today
total = Records.where(created_at: from..to).group("date(created_at)").count
list = total.values

只有在某些日期没有记录时才会显示的问题,只会被忽略。

所以不要这样:

list = [0,4,3,0,3,0,1]

我明白了:

list = [4,3,3,1]

嗯,我想我理解为什么我这样做,因为查询记录而不是日期。

我可以循环from.upto(to)并在each一个do对数据库进行查询,获取这些计数并构建我的小清单 - 或其他非常 - 但是,是否有更简洁的解决方案不涉及大量查询?

1 个答案:

答案 0 :(得分:1)

我知道这不是一个完美的解决方案。但它不涉及任何额外的查询。对于from和to之间的所有日期,基本上反向合并散列和零计数。

from = 7.days.ago.to_date
to = Date.today
date_hash = {}
(from..to).each{|date| date_hash[date] = 0}
total = Records.where(created_at: from..to).group("date(created_at)").count
total.reverse_merge!(date_hash)