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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With