pzin
pzin

Reputation: 4248

Count records by date returning zero values

I am trying to find a way to output the number of records of each day between two given dates:

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

There is just the problem that when in some dates are no records, it wouldn't be displayed, would be just ignored.

So instead of this:

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

I get this:

list = [4,3,3,1]

Well, I think I understand why I get it so, because of querying records and not dates after all.

I could do a loop from.upto(to) and on each one do a query to the DB, get those counts and build so my little list —or something else very dirty— but, is there a more clean solution not involving lots of queries?

Upvotes: 0

Views: 508

Answers (1)

usha
usha

Reputation: 29349

I know this is not a perfect solution. But it doesn't involve any extra query. Basically reverse merge a hash with zero count for all the dates between from and 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)

Upvotes: 1

Related Questions