[英]Rails 3 Counting Records by Date
我正在嘗試通過模型方法構建一個看起來像這樣的數組:
[['3/25/13', 2], ['3/26/13', 1], ['3/27/13', 2]]
日期是字符串,后面的數字是表/對象的count
。
我現在有以下模型方法:
def self.weekly_count_array
counts = count(group: "date(#{table_name}.created_at)", conditions: { created_at: 1.month.ago.to_date..Date.today }, order: "date(#{table_name}.created_at) DESC")
(1.week.ago.to_date).upto(Date.today) do |x|
counts[x.to_s] ||= 0
end
counts.sort
end
但是,它不能正確返回計數(所有值均為零)。 我已經檢查了SO上類似的問題,但似乎也無法使它們起作用。
有人可以幫助(1)讓我知道這是否是最好的方法,並且(2)就上述代碼可能出現的問題提供一些指導(如果是)? 謝謝!
如果您願意,可以使用它作為模板
def self.period_count_array(from = (Date.today-1.month).beginning_of_day,to = Date.today.end_of_day)
where(created_at: from..to).group('date(created_at)').count
end
這將返回一個哈希值,其中日期作為鍵,計數作為值。 (Rails 3.2.x)
也許這就是您想要做的?
class YourActiveRecordModel < ActiveRecord::Base
def.self weekly_count_array
records = self.select("COUNT(id) AS record_count, DATE(created_at) AS created")
.group("DATE(created_at)")
.where("created_at >= ?", 1.month.ago.to_date)
.where("created_at <= ?", Date.current)
records.each do |x|
puts x.record_count
puts x.created # 2013-03-14
# use I18n.localize(x.created, format: :your_format)
# where :your_format is defined in config/locales/en.yml (or other .yml)
end
end
end
@Aditya Sanghi的精彩回答。
如果您有確切的要求,則可以選擇:
def self.weekly_count_array
records = select('DATE(created_at) created_at, count(id) as id').group('created_at')
1.week.ago.to_date.upto(Date.today).map do |d|
[d, records.where('DATE(created_at) = ?', d.to_date).first.try(:id) || 0]
end
end
您不需要執行計數的過程。 只需對此執行查詢。
def self.weekly_count_array
select("created_at, COUNT(created_at) AS count")
where(created_at: 1.month.ago.to_date..Date.today)
group("created_at")
order("created_at DESC")
end
建立在@kiddorails答案上,
所以不要向數據庫發出很多請求,而是從ActiveRecord創建哈希
&將該組從.group('created_at')更改為.group('DATE(created_at)')以根據日期進行設置
def self.weekly_count_array
# records = select('DATE(created_at) created_at, count(id) as id').group('created_at')
records_hash = Hash[Download.select('DATE(created_at) created_at, count(id) as id').group('DATE(created_at)').map{|d|[d.created_at, d.id] }]
1.month.ago.to_date.upto(Date.today).map do |d|
[ d, records_hash[d.to_date] || 0 ]
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.