views:

219

answers:

3

I'm trying to generate a report for the average number of calls a person makes per-day. The following generates the correct list, but if a user didn't make any calls a certain day it doesn't show up. Very much like this problem

Going through the above link, i have this code:

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]}

At first, I just stuck call_aves into the value for Open Flash Charts, and it broke it, kind've looked like it went into an infinite loop. So I went into my debugger to see what was happening.

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

As I go up in the array, i notice it's only incrementing by seconds, not by days. For example:

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

How do I get this to go up by the day, not the second?

A: 

Try using

Date.today.at_beginning_of_month.to_s(:db)

and

Date.today.tomorrow.to_s(:db)

instead.

Jarrod
Tried this already, throws an exception. undefined method `strftime' for "2009-08-01 00:00:00":String. strftime and to_s don't like each other.
Ryan
It looks like you're using strftime to filter the time out of a Time object, leaving just the date. Using a Date object doesn't include time, so strftime isn't needed. Just use to_s and a date format. More info on date formats: http://onrails.org/articles/2008/08/20/what-are-all-the-rails-date-formats
Jarrod
A: 

Try using

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] ) }
John Hyland
A: 

As you've found out, Time is internally represented in a count of seconds, and a range of time produces a range of seconds. A range of dates, on the other hand, produces a range of dates.

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

You don't need to stringify dates for ActiveRecord -- Rails does that for you. For example, for a model with timestamps:

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

gets you objects created within the past week. Note that I make no pretense of converting data objects so that MySQL will like them -- that is ActiveRecord's job.

Patrick McKenzie