-2

I have a rake task in my rails app which calculate bonuses:

namespace :all_bonus do
 desc "all given bonuses"
 task given_bonuses: :environment do
   points = 0
   Bonus.find_each do |bonus|
     points += bonus.points
   end

   puts Bonus.count
   puts points
 end
end

Find each method is loaded memory and I want to change it using SQL. How can I do it?

Damir Nurgaliev
  • 341
  • 5
  • 19
  • Possible duplicate of [Rails how to sum columns?](http://stackoverflow.com/questions/8874291/rails-how-to-sum-columns) – Holger Just Dec 22 '16 at 16:10

1 Answers1

2

Try something like

Bonus.sum(:points)

It translates into something like this SQL

SELECT SUM(`bonuses`.`points`) FROM `bonuses`
Ursus
  • 29,643
  • 3
  • 33
  • 50