Reputation: 547
I hope someone can help. I suspect this is an embarrassingly newbie question, but then, I'm embarassingly new. I've tried everywhere I can think of for an answer to this and tried every permutation I can think of.
Task: I'm working through an example in a Ruby tutorial that manages a online shopping cart. The task is to create a button next to each item displayed in the cart, enabling you to decrement the amount of a single item by 1.
Problem: When I click on the "Decrement" button in my view next to an item with a quantity of one, it disappears from the cart, as expected. But when I click on the button next to an item with a quantity of more than one, nothing happens.
Code
View:
<td><%= button_to("Decrement", decrement_line_item_path(line_item), method: :post ) %>
</td>
(I have set a member route in routes.rb so that it accesses the decrement action on "POST")
Controller:
def decrement
@cart = set_cart
@line_item = @cart.line_items.find_by(params[:id])
@line_item = @cart.decrement_line_item_quantity(@line_item.id)
respond_to do |format|
format.html {redirect_to store_url}
end
end
(there's a set_cart method in a concerns file that just gets or sets the cart based on a session, and I know that works).
Model:
def decrement_line_item_quantity(item_id)
item_to_decrement = line_items.find_by(id: item_id)
if item_to_decrement.quantity > 1
item_to_decrement.quantity -= 1
else
item_to_decrement.destroy
end
item_to_decrement
end
My debugger says that:
But the value for the line item's quantity in the actual cart appears to be unchanged in the controller method. I check @cart.line_items.find_by(params[:id]).quantity in my debugger after returning from the model method, and it hasn't changed.
This means that when I come to render my cart later, the quantity of an item with multiple units is not decreased, and so nothing happens.
Can someone tell me what I missed? This is the very first time I've used Stack Overflow, so I'm still learning. Have read the guidelines, and I hope I'm following them appropriately. Apologies for any transgressions and thanks so much in advance.
Upvotes: 2
Views: 64
Reputation: 3368
You have to save the record after you decrement the quantity, otherwise the change in the quantity will not get persisted to the database:
def decrement_line_item_quantity(item_id)
item_to_decrement = line_items.find_by(id: item_id)
if item_to_decrement.quantity > 1
item_to_decrement.quantity -= 1
item_to_decrement.save
else
item_to_decrement.destroy
end
item_to_decrement
end
Upvotes: 1