I'm trying to create a loop for the last 15 days to give me counts of records on each day.
So @records should be an array of counts for the last 15 days.
However, the record stores dates as datetime (as you know), and I'm trying to reference any time within a single day.
@records = []
15.times do |i|
bar = Records开发者_StackOverflow.all.count(
:type => 'large',
:created_at => ((i-1).days.ago..i.days.ago)
)
@records << bar
end
Thoughts? Thanks!
Record.where("date(created_at) > ?", 15.days.ago).group("date(created_at)").count
should give records count by days.
Sample Output:
{"2011-07-02"=>4,
"2011-07-04"=>5,
"2011-07-05"=>16,
"2011-07-06"=>12,
"2011-07-11"=>19}
You can use SQL to do the count without instantiating a lot of Record
objects (which uses memory/time)
ActiveRecord::Base.connection.select_rows('SELECT DATE(created_at) AS d, COUNT(*) AS c FROM my_records_table GROUP BY DATE(created_at)')
This will give you an array of arrays:
> pp ActiveRecord::Base.connection.select_rows('SELECT DATE(created_at) AS d, COUNT(*) AS c FROM my_records_table GROUP BY DATE(created_at)')
[["2011-06-23", "326"],
["2011-06-24", "337"],
["2011-06-25", "334"],
["2011-06-26", "353"],
["2011-06-27", "210"],
["2011-06-28", "330"],
["2011-06-29", "331"],
["2011-06-30", "338"],
["2011-07-01", "335"],
["2011-07-02", "366"],
["2011-07-03", "320"],
["2011-07-04", "338"],
["2011-07-05", "338"],
["2011-07-06", "299"],
["2011-07-07", "326"],
["2011-07-08", "314"],
["2011-07-09", "331"],
["2011-07-10", "335"],
...but I just saw dexter's answer and that is WAY better :)
精彩评论