Home > Software engineering >  Rails sum all prices inside a record
Rails sum all prices inside a record

Time:05-13

I have a model Products that belongs_to model Kit

Kit has_many Products

¿How can I sum all of the prices of each product that belongs to a kit?

I tried with no luck:

@kitprice = Kit.products.price.sum

CodePudding user response:

Try this:

@kitprice = kit.products.sum(:price)

In my case i have wallet with many operations

wallet = Wallet.first
amount = wallet.operations.sum(:amount)

CodePudding user response:

Question is slightly ambiguous. Assuming you have an instance of Kit named as kit, and a kit has many product objects; following would get you the desired result.

sum = 0
kit_id = <enter kit id here>
kit = Kit.find_by_id(kit_id)

# iterate through every product object and compound price here
kit.products.each{|product| sum = sum   product.price} 

puts sum

Basically you need to iterate through every product object and compute the sum, since it's a has many relationship.

CodePudding user response:

This will give you every kit with the sum of it's products, i assume there is a column named name in your kit model

@kit_products_price = Kit.includes(:products).group(:name).sum('products.price')

If you want the sum of all the kit products :

@kit_price = Kit.includes(:products).sum('products.price')

CodePudding user response:

The following should work I believe:

Active Record collection

@total = kit.products.sum("price")

Ruby array

@total = kit.products.sum(&:price)
  • Related