2011-08-29 60 views
2

我正在嘗試創建最近15天的循環,以便每天都能記錄計數。RoR:查詢日期時間從一天開始計數記錄

因此@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 

想法?謝謝!

回答

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} 
+0

小心寫一些Arel的文檔?也許是一堆Arel單線隊員? –

+0

實際上我偷了它正確的Arel官方文檔:D http://goo.gl/ca9nJ – dexter

+0

感謝您的答覆,但不包括NULL,我需要。你將如何.group()迭代? – Galen

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

...但我只看到了德克斯特的答案,這是更好的方式:)

相關問題