ana
ana

Reputation: 485

Calculate sum of columns value in Ruby on Rails

I want to calculate the sum of the values in a column. For example:

@items = Item.find_all_by_cart_id(cart)

Item has column quantity. I want the sum of the @items quantity.

Upvotes: 0

Views: 727

Answers (2)

Raghuveer
Raghuveer

Reputation: 2638

Try this

@items = Item.find_all_by_cart_id(cart).sum(:quantity)

Upvotes: 1

aromero
aromero

Reputation: 25761

items_quantity = @items.map(&:quantity).sum

Upvotes: 1

Related Questions