date_from = Date.parse '2010-06-01'
date_to = Date.parse '2010-07-01'
click_counts = (date_from..date_to).map{|date|
[date, Click.count(:conditions => {:date_stamp => date})]
}
will return an array of [date, count]
pairs for a given period. However, this will issue a database query for each day in the date range.
One common solution to solve such queries is to create a database table filled with all dates (say, for previous and next 10 years from now), and then perform a JOIN
, similar to:
SELECT d.date, COUNT(c.date_stamp)
FROM dates d
LEFT JOIN clicks c ON d.date = c.date_stamp
GROUP BY d.date
which will return all the click counts in a single query.
Or, as a third solution, you can get click counts for existing dates:
Click.find(:all,
:select => "date_stamp, count(*) as count",
:group => 'date_stamp',
:conditions => ["date_stamp >= ? and date_stamp < ?", date_from, date_to])
and add "empty" days in Ruby.