0

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.

1
  • Have you tried using inject Commented May 13, 2013 at 13:59

2 Answers 2

1
items_quantity = @items.map(&:quantity).sum
Sign up to request clarification or add additional context in comments.

Comments

1

Try this

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

1 Comment

This is a a cleaner, model related way to do this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.