def remove_items
line_items.each do |item|
@ci = Product.find(item.id)
@ci.quantity = @ci.quantity.to_i - 1
end
您好,我正在尝试使用该项的ID,然后将该ID与产品匹配,然后将-1减去该产品的数量属性。
我目前收到此错误。
TypeError in OrdersController#create
can't convert nil into String
有什么问题? 感谢
OrderController#创建 请记住,由于正在进行,代码很邋.. :)
def create
@order = current_cart.build_order(params[:order])
@order.ip_address = request.remote_ip
@cart = current_cart
if @order.save
if @order.purchase
@order.status = "paid"
@cart.remove_items
@cart.destroy
render :action => "success"
else
@order.status = "failed"
@cart.destroy
render :action => "failure"
end
else
render action: "new"
end
端
我认为这是堆栈跟踪
[0m
←[1m←[35mLineItem Load (0.0ms)←[0m SELECT "line_items".* FROM "line_items" WH
ERE "line_items"."cart_id" = 129
←[1m←[36mProduct Load (0.0ms)←[0m ←[1mSELECT "products".* FROM "products" WHE
RE "products"."id" = ? LIMIT 1←[0m [["id", 147]]
Completed 500 Internal Server Error in 5762ms
TypeError (can't convert nil into String):
app/controllers/application_controller.rb:60:in `+'
app/controllers/application_controller.rb:60:in `record_not_found'
答案 0 :(得分:1)
根据你的评论,这应该可以解决问题:
# application_controller.rb
def record_not_found
flash[:alert] = "Cannot find record number #{params[:id]}. Displaying all records."
redirect_to root_path
end
但如果我是你,我不会在警告信息中输出params [:id]。只是说没有找到记录,basta。
flash[:alert] = "Cannot find record. Displaying all records."
您也可以在一行中执行此操作:
redirect_to root_path, alert: "Cannot find record. Displaying all records."
要修复remove_items
方法中的逻辑,您需要在最后实际保存对象:
def remove_items
line_items.each do |item|
ci = Product.find(item.id)
ci.quantity = ci.quantity.to_i - 1
ci.save
end
end
答案 1 :(得分:0)
看起来您正在从头开始构建购物车应用。您是否考虑过使用Spree等现有平台?
答案 2 :(得分:0)
让DB一次性减少所有产品是个更好的主意:
def remove_items
Product.where(id:line_items.map(&:id)).update_all('quantity = quantity - 1')
end
或更好:
def remove_items
Product.decrement_counter(:quantity, line_items.map(&:id) )
end
如果无法找到产品,这些会更快,避免错误,如果您同时运行多个进程,也可以避免Race Condition。