0

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

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查询,获取这些计数并构建我的小列表 - 或者其他非常的东西- 但是,有没有更干净的解决方案不涉及大量查询?

4

1 回答 1

1

我知道这不是一个完美的解决方案。但它不涉及任何额外的查询。基本上反向合并从和到之间所有日期的零计数哈希。

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)
于 2013-10-15T14:12:30.867 回答