sjsc
sjsc

Reputation: 4672

Ruby on Rails: How do I correctly define a method in the model to total up a column?

I'm trying total up all "amount" columns with a definition in the model like so:

  def self.total
    self.all.collect(&:amount).sum
  end

With that, "Recipe.total" works as expected. However, I'm using a plugin that passes "Recipe.find(:all)", and I can't seem to pass that to the method to find the total. That is:

Recipe.find(:all).total # doesn't work

Is there a way to define the method in my model differently to make Recipe.find(:all).total work like Recipe.total?

Upvotes: 4

Views: 454

Answers (2)

lest
lest

Reputation: 8100

You can write your method as:

def self.total
  self.sum(:amount)
end

And then you can use it also with named scopes:

Recipe.total # without any scopes
Recipe.my_custom_named_scope.total # with your custom named scope

Another variant is to override find method for that model:

def self.find(*args)
  result = super
  if args[0] && args[0] == :all
    def result.total
      self.sum(&:amount)
    end
  end
  result
end

Then you get exactly what you want, you'll be able to write Recipe.find(:all).total.

Upvotes: 5

Jonathan
Jonathan

Reputation: 16359

Check out the Calculation Module

It has methods for: sum,average,count, etc ...

Its baked into ActiveRecord.

So you would want to write:

Recipe.sum(:total)

Have fun!

Upvotes: 3

Related Questions