2009-08-13 70 views
0

我正在尝试生成每天平均打电话数的报告。以下内容会生成正确的列表,但如果用户在某一天没有打电话,则不会显示。 Very much like this problem平均每天在导轨上使用红宝石

通过上面的链接去,我有这样的代码:

from_date = Time.now.at_beginning_of_month.to_s(:db) 

to_date = Time.now.tomorrow.to_s(:db) 

ave_calls = @current_user.calls.average(:num_of_calls, group => "DATE(calls.start_time_stamp)", 
:conditions => ["calls.created_at BETWEEN ? AND ?",from_date, to_date]) 

call_aves = (Time.now.at_beginning_of_month..Time.now.tomorrow).map{|dt| [dt, ave_calls[dt.strftime "%Y-%m-%d"] || 0]} 

起初,我只是坚持call_aves成打开Flash图表值,并打破了它,kind've看起来像它去进入无限循环。所以我进入了我的调试器,看看发生了什么。

irb(#<ReportsController:0x47b7524>):008:0> call_aves[0] 
=> [Sat Aug 01 00:00:00 -0400 2009, 0] 

当我在数组中,我注意到它只是递增秒,而不是几天。例如:

irb(#<ReportsController:0x47b7524>):009:0> call_aves[30] 
=> [Sat Aug 01 00:00:30 -0400 2009, 0] 

我该如何得到这一天,而不是第二?

回答

0

使用

Date.today.at_beginning_of_month.to_s(:db) 

Date.today.tomorrow.to_s(:db) 

,而不是尝试。

+0

试过这个,抛出异常。未定义的方法'strftime'为“2009-08-01 00:00:00”:String。 strftime和to_s不喜欢彼此。 – Ryan 2009-08-13 16:13:39

+0

看起来您正在使用strftime来过滤Time对象的时间,只剩下日期。使用Date对象不包含时间,所以不需要strftime。只需使用to_s和日期格式即可。有关日期格式的更多信息:http://onrails.org/articles/2008/08/20/what-are-all-the-rails-date-formats – Jarrod 2009-08-13 18:16:19

0

使用

days = (Date.today.at_beginning_of_month..Date.today.tomorrow) 
call_aves = days.map { |dt| call_aves.push([dt, ave_calls[dt.to_s(:db)] || 0]) } 
0

正如你已经找到了尝试,时间在内部以秒计数表示,一段时间内的生产一系列秒。另一方面,日期范围会产生一系列日期。

(Date.today.beginning_of_month..Date.today).each do |date| 
    #copy paste your code here 
end 

你不需要为ActiveRecord过滤日期 - Rails可以为你做到这一点。例如,对于具有时间戳的模型:

Model.find(:conditions => ["created_on > ?", Date.today - 7.days]) 

获取您在过去一周内创建的对象。请注意,我没有佯装转换数据对象,以便MySQL会喜欢它们 - 这就是ActiveRecord的工作。