0

I'm building a call tracking application, as a way to learn Rails and Twilio. Right now, I am trying to follow Ryan Bates' tutorial to create a graph that shows users the number of phone calls they have per day.

The model works like so -- > Phone has_many calls

What I would like to do, is to create a class method that would allow me to do something like

phone.calls.total_on(date)

This would show the total calls a particular phone has on a particular date.

Here's the code currently in my Phone model

  def self.total_on(date)
    where("date(calls_at) = ?", date).sum( self.calls.count )
  end

What probably is wrong with the code is sum(self.calls.count). This would count all the calls, regardless of date, if I'm in the right direction.

How would I go about making a class method that would count the calls on a particular date?

Thanks for sticking with me so far! Your thoughts greatly appreciated.

Stepan Parunashvili
  • 2,627
  • 5
  • 30
  • 51

2 Answers2

1

Simply this:

def total_on(date)
  self.calls.where("placed_at >= ? AND placed_at <= ?", date.beginning_of_day, date.end_of_day).count
end

Assuming that you've got a Phone object and you want to know how many associated calls for that object happened on a given day. This method should be an instance method, not a class method. I don't understand why it would be a class method if you're wanting to see how many calls there've been for a particular phone on a particular day.

If you use by_star, the above code would be this:

def total_on(date)
  self.calls.by_day(date).count
end
Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261
  • Thanks for the answer Ryan! I think this is getting closer to what I'm trying to do. I'm still having trouble, but I think now the problem is with the code in the view. I get the error : undefined method `to_f' for # . The new stackoverflow question is here: http://stackoverflow.com/questions/12845647/undefined-method-to-f-for-activerecordrelation0x472d0a0 . Your thoughts appreciated – Stepan Parunashvili Oct 11 '12 at 17:55
  • My mistake, I missed the `count` on the end. – Ryan Bigg Oct 11 '12 at 20:29
1

Try the following

  def self.total_on(date)
    query = select("calls.id").where("date(calls_at) = ?", date).joins(:calls)
    query.count
  end
Mahesh
  • 6,378
  • 2
  • 26
  • 35