Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 732
sjsc Avatar asked Feb 26 '23 09:02

sjsc


1 Answers

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.

like image 93
lest Avatar answered May 05 '23 15:05

lest