1
    def remove_items
    line_items.each do |item|
        @ci = Product.find(item.id)
        @ci.quantity = @ci.quantity.to_i - 1
end

Hello, I am trying to use the id of the item and then match the id with a product and then minus 1 to the quantity property of that product.

I currently get this error though.

TypeError in OrdersController#create

can't convert nil into String

What is wrong? Thanks

OrderController#create Please bear in mind code is scruffy due to being in progress. :)

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

end

I think this is the stack trace

[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'
4

3 回答 3

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]。就说没有找到记录,混蛋。

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
于 2013-06-05T19:27:54.843 回答
0

Looks like you're buding a shopping cart app from scratch. Have you considered using an existing platform, like Spree?

于 2013-06-05T18:23:56.870 回答
0

让数据库一次减少所有产品是一个更好的主意:

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

这些更快,如果找不到产品,可以避免错误,如果您有多个进程同时运行,也可以避免竞争条件。

于 2013-06-06T00:37:19.260 回答