How to calculate points using SQL not ruby

53 views Asked by At

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?

1

There are 1 answers

0
Ursus On

Try something like

Bonus.sum(:points)

It translates into something like this SQL

SELECT SUM(`bonuses`.`points`) FROM `bonuses`