0

I have:

class Vehicle << ActiveRecord::Base

  def odometer
    metric ? self.read_attribute(:odometer).miles.to.kilometers : self.read_attribute(:odometer)
  end

end

When metric = true and I do vehicle.odometer it works, I get kilometers.

But when I call an aggregate vehicles.sum(:odometer) it does not work, as if the method odometer is not being called.

Bruno
  • 6,211
  • 16
  • 69
  • 104

1 Answers1

1

It's probably because your vehicles is an ActiveRelation object and calling sum on it will calculate the sum using sql query(not using the method you have defined)

Query generated will be

select sum(vehicles.odometer) from vehicles where ...

If you want your method to be called, do the following

 vehicles.sum(&:odometer)
usha
  • 28,973
  • 5
  • 72
  • 93
  • Your solution worked. Do you happen to know where can I find documentation on using the '&'? – Bruno Nov 18 '13 at 18:45
  • It does not seem to be working with `vehicles.maximum(&:speed)` – Bruno Nov 18 '13 at 18:54
  • `vehicles.sum(&:odometer)` is another way of writing `vehicles.sum{|v| v.odometer}`. You can find some explanation here -> http://stackoverflow.com/questions/1961030/ruby-ampersand-colon-shortcut – usha Nov 18 '13 at 19:17
  • `average` and `maximum` doesn't work because they are not defined in Enumerable – usha Nov 18 '13 at 19:20