我希望有人能帮忙。我怀疑这是一个令人尴尬的新手问题,但我是一个尴尬的新手。我已经试过了我能想到的所有地方来寻找答案,并尝试了我能想出的每一种排列。
任务:我正在学习Ruby教程中管理在线购物车的一个示例。任务是在购物车中显示的每个项目旁边创建一个按钮,使您能够将单个项目的数量减少1。
问题:当我点击视图中数量为1的项目旁边的"递减"按钮时,它会从购物车中消失,正如预期的那样。但是,当我点击一个数量超过一个的项目旁边的按钮时,什么都不会发生。
代码
视图:
<td><%= button_to("Decrement", decrement_line_item_path(line_item), method: :post ) %>
</td>
(我在routes.rb中设置了一个成员路由,以便它访问"POST"上的递减操作)
控制器:
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
(在关注文件中有一个set_cart方法,它只是基于会话获取或设置cart,我知道这很有效)。
型号:
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
我的调试器说:
- item_to_decrement.quantity按预期在模型方法中减少
- @controller方法中的line_item.quantity也如预期的那样减少
但是实际购物车中商品数量的值在控制器方法中似乎没有变化。从模型方法返回后,我在调试器中检查@cart.line_items.find_by(params[:id]).guosity,它没有改变。
这意味着,当我稍后来渲染我的购物车时,具有多个单位的物品的数量不会减少,因此不会发生任何事情。
有人能告诉我我错过了什么吗?这是我第一次使用Stack Overflow,所以我还在学习。已经阅读了指导方针,我希望我能适当地遵循它们。为任何违法行为道歉,并提前表示感谢。
您必须在减少数量后保存记录,否则数量的变化将不会持久化到数据库中:
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