'Rails sum all prices inside a record
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
Solution 1:[1]
Try this:
@kitprice = kit.products.sum(:price)
In my case i have wallet with many operations
wallet = Wallet.first
amount = wallet.operations.sum(:amount)
Solution 2:[2]
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.
Solution 3:[3]
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')
Solution 4:[4]
The following should work I believe:
Active Record collection
@total = kit.products.sum("price")
Ruby array
@total = kit.products.sum(&:price)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Vasanth Saminathan |
| Solution 3 | Bouaik Lhoussaine |
| Solution 4 | Bright Mensah |
