Another method is ActiveRecord::Calculations.pluck , then Enumerable#sum on the external array and again on the internal pair of the array:
Student .where(id: student_id) .pluck(:total_mark, :marks_obtained) .map(&:sum) .sum
The resulting SQL query is simple:
SELECT "students"."total_mark", "students"."marks_obtained" FROM "students" WHERE "students"."id" = $1
The original pluck result is an array of pairs of arrays, for example:
[[10, 5], [9, 2]]
.map(&:sum) will run sum for each pair, adding up the pair and smoothing the array:
[15, 11]
Finally .sum on a flattened array will result in a single value.
Edit:
Note that although there is only one query, your database will return a row of results for each record matched in where . This method uses ruby ββto perform the summation, so if there are many records (i.e., Thousands), it may be slower than SQL to do the calculations themselves, as indicated in the accepted answer.
Marc greenstock
source share