RoR:在查询日期时间从一天开始计算记录

时间:2011-08-29 15:47:28

标签: ruby-on-rails-3 datetime

我正在尝试创建一个过去15天的循环,以便每天给我一些记录。

所以@records应该是过去15天的一系列计数。

然而,记录将日期存储为日期时间(如您所知),并且我试图在一天内的任何时间参考。

@records = []

      15.times do |i|
        bar =  Records.all.count( 
          :type => 'large',
          :created_at => ((i-1).days.ago..i.days.ago)
          )
        @records << bar
      end

思考?谢谢!

2 个答案:

答案 0 :(得分:8)

Record.where("date(created_at) > ?", 15.days.ago).group("date(created_at)").count

应该按天计算记录数。

示例输出:

 {"2011-07-02"=>4,
 "2011-07-04"=>5,
 "2011-07-05"=>16,
 "2011-07-06"=>12,
 "2011-07-11"=>19}

答案 1 :(得分:1)

您可以使用SQL进行计数,而无需实例化大量Record个对象(使用内存/时间)

ActiveRecord::Base.connection.select_rows('SELECT DATE(created_at) AS d, COUNT(*) AS c FROM my_records_table GROUP BY DATE(created_at)')

这将为您提供一系列数组:

> 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"],

...但我刚看到德克斯特的答案,那就更好了:)