mercredi 2 novembre 2016

sum() or group() virtual attributes in ruby on rails

let's say I have a model like this:

class Surface < ActiveRecord::Base
  attr_accessible :width, :length

  def area
     self.width * self.length
  end
end

Where @surface.area returns the area of a surface. Now, lets say I have many surfaces called @surfaces and I want to sum all areas. How do I do this?

My favorite solution would look like this:

@surfaces.sum(:area)

But it does not work. So how can I call .sum() or .group() or any similar functions on a virtual attributes like this in rails? I would like to avoid .each do |surface| calls.

Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire