I’m running the following method and I’m successfully passing two arguments (inventory, quantity) into the method. However I’m incorrectly using .first and .each methods. I’m attempting to replace .each with the .select to select for the cart item with the Inventory id: 6
possible .each replacement: (does not function) inventory_to_increment = @items.select{|item| item_id == inventory}
def increment_inventory_quantity(inventory, quantity)
inventory_to_increment = @items.each{|item| item.inventory == inventory}
unless inventory_to_increment.empty?
inventory_to_increment = inventory_to_increment.first
else
# error handling here
end
inventory_to_increment.quantity = quantity.to_i
end
I’ve used Ruby Debugger, to debug my code:
inventory_to_increment = @items.each{|item| item.inventory == inventory}
p inventory = 6
unless inventory_to_increment.empty?
CartItem:0x102c4a4c0 @quantity=22, @inventory=#<Inventory id: 1
CartItem:0x102c49638 @quantity=2, @inventory=#<Inventory id: 8
CartItem:0x102c48918 @quantity=4, @inventory=#<Inventory id: 50
CartItem:0x102c47b80 @quantity=2, @inventory=#<Inventory id: 6
inventory_to_increment.first
CartItem:0x102c4a4c0 @quantity=22, @inventory=#<Inventory id: 1
inventory_to_increment.quantity = quantity.to_i
= 3
I’ve tried several combinations and I need some basic Ruby array guidance. Thank you in advance!
UPDATE OUTPUT FOR ANSWER
inventory_to_increment = @items.select{|item| item.inventory_id == inventory}
(rdb:1) list
[21, 30] in /Users/justin/cart/app/models/cart.rb
21
22
23 def increment_inventory_quantity(inventory, quantity)
24 debugger
25
=> 26 inventory_to_increment = @items.select{|item| item.inventory_id == inventory}
27 unless inventory_to_increment.empty?
28 inventory_to_increment.first
29 end
30
(rdb:1) p @items
[#<CartItem:0x102df1828 @quantity=22, @inventory=#<Inventory id: 1>>, #<CartItem:0x102df09a0 @quantity=2, @inventory=#<Inventory id: 8>>, #<CartItem:0x102ded908 @quantity=21, @inventory=#<Inventory id: 50>>]
(rdb:1) p inventory
50
(rdb:1) p quantity
"11"
(rdb:1) p item.inventory.id
NameError Exception: undefined local variable or method `item' for #<Cart:0x102df18f0>
(rdb:1) p item.inventory_id
NameError Exception: undefined local variable or method `item' for #<Cart:0x102df18f0>
(rdb:1) next
/Users/justin/.gem/ruby/1.8/gems/actionpack-2.3.5/lib/action_controller/rescue.rb:162
rescue_action(exception)
It seems
Inventoryis an object and if so it’s likely that youritem.inventory == inventorywill not work as expected. Let’s say you have an Item class.and then you create two objects and compare them:
This is because you will compare the object ids (0xb7b733bc to 0xb7b6b7c0) instead of the content of the objects.
It then seems you only want to add to the
quantityto the first item matching the inventory id. If that is correct then you can try something like this