patternrubyrailsMinor
Instance variables and do loops in ruby on rails
Viewed 0 times
loopsinstancerailsvariablesrubyand
Problem
I find my self often doing things like this in Ruby on Rails:
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?
@count = 0
LineItem.all.each do |item|
if (item.cart_id == @cart.id)
@count += item.quantity
end
endSo 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?
Solution
If you work with database you can do this more efficiently with sql request:
This is equivalent sql query
LineItem.where(:card_id => @card.id).sum('quantity')This is equivalent sql query
SELECT SUM(items.identity) FROM items WHERE items.card_id = ?;Code Snippets
LineItem.where(:card_id => @card.id).sum('quantity')SELECT SUM(items.identity) FROM items WHERE items.card_id = ?;Context
StackExchange Code Review Q#13130, answer score: 6
Revisions (0)
No revisions yet.