jeudi 12 septembre 2019

sum method alternatives for active records

I am in a legacy Ruby on Rails project. Rails v2.3.9.

I have a model class product, in database there is products table.

class Product < ActiveRecord::Base

  ...
end

There is price attribute which is a integer type.

I got all products (ActiveRecords) at some point. I need to calculate the total price of all products I got. I know I can do:

total_price = all_products.sum(&:price)

It works.

But it also triggers a database query SELECT sum(...). Is there an alternative way to calculate the summation of price of all products without triggering any database query? I know I can use for loop, but I wonder any other ways?

Aucun commentaire:

Enregistrer un commentaire