views:

35

answers:

1

Not sure on my Ruby syntax here.

I want to define a method that I can call like this: client.invoices.average_turnaround. So my average_turnaround method needs to work with a collection of ActiveRecord objects.

Here's my code thus far:

class Invoice < ActiveRecord::Base
  ...
  def self.average_turnaround
    return self.map(&:turnaround).inject(:+) / self.count
  end
end

So I'm trying to find the sum of the turnaround times for each invoice, then divide it by the total number of invoices.

Ruby is complaining that there is no map method defined for Class. I was expecting self to be an Array.

How do I write a method that works on a collection of Invoices and uses the map function? Where am I going wrong?

+2  A: 

You defined a class method, which is called on the class itself. What you need is an association extension. The method should be defined on your client model like this:

class Client < ActiveRecord::Base
  has_many :invoices do
    def average_turnaround
      return map(&:turnaround).inject(:+) / count
    end    
  end
Teoulas
Fantastic - another useful piece in the the Rails puzzle :)
nfm