3
\$\begingroup\$

I find my self often doing things like this in Ruby on Rails:

@count = 0
LineItem.all.each do |item|
 if (item.cart_id == @cart.id)
 @count += item.quantity
 end
end

So many things look wrong with this, but I want to initialize my variable (@count) before the loop, and then be able to use it after I'm out of the loop.

Is there a better way to do this?

asked Jun 27, 2012 at 15:25
\$\endgroup\$

2 Answers 2

1
\$\begingroup\$

From what I can see, you are just collecting the item.quantity of all matching items. This can be accomplished by

@count = LineItem.all.find_all{|i| i.cart_id == @cart.id}.map{|i| i.quantity}.inject(0,:+)

Do you mean that you might be doing something else with in the cart_id check?

answered Jun 27, 2012 at 15:54
\$\endgroup\$
1
  • \$\begingroup\$ Both this and the other answer work. This one seems to complete the queries faster. I'm using Postgres. Thank you both! \$\endgroup\$ Commented Jun 28, 2012 at 17:41
6
\$\begingroup\$

If you work with database you can do this more efficiently with sql request:

LineItem.where(:card_id => @card.id).sum('quantity')

This is equivalent sql query

SELECT SUM(items.identity) FROM items WHERE items.card_id = ?;
answered Jun 27, 2012 at 22:23
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.