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

您好,我正在嘗試使用該項目的id,然後將該id與產品匹配,然後減去該產品的quantity屬性的1。ruby​​ on rails查詢

我目前得到這個錯誤。

TypeError in OrdersController#create 

can't convert nil into String 

出了什麼問題? 謝謝

OrderController#create 請記住,由於正在進行,代碼很sc code。 :)

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

在控制器和堆棧跟蹤中發佈完整操作。 – fotanus

+0

向我們展示'OrdersController'上'create'的作用和'rake routes'的輸出 –

+0

Added OrderController。現在將獲得耙路線 – baihu

回答

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 
+0

謝謝,即解決了錯誤,但邏輯不工作。即使當我硬編碼此,沒有什麼變化 \t \t DEF remove_items \t \t \t [在] CI = Product.find(10) \t \t \t [在] Cl .quantity = 0 \t \t結束 對象的實例或實際語法本身存在問題嗎? 謝謝 – baihu

+0

@ baihu更新了答案 – Daniel

+0

輝煌。謝謝丹尼爾 – baihu

0

你好像從長大?從頭開始一個購物車的應用程序。您是否考慮過使用Spree等現有平臺?

+0

一個答案,我不知道存在這樣的事情,但我喜歡建築的東西反正自己的經驗。 – baihu

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如果你有同時運行多個進程。