简体   繁体   中英

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?

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 .

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM