2016-04-19 32 views
0

我對Rails很陌生,所以可能是我犯的一個愚蠢的錯誤,只需要有人指出。Rails錯誤:未定義的方法`add_product'爲零:NilClass

構建一個小型購物車應用程序。當我點擊 '加入購物車',它拋出了這個錯誤:

NoMethodError in LineItemsController#create 
undefined method `add_product' for nil:NilClass 

參數:

{"authenticity_token"=>"uZ6zOfA237VBzt3Pz2tEBESzjv2pg+Vhx73DTolL8f76ANS80qiU6+wcN8Tvq/r+CSZvzxnkKll/ZJl2H2XePQ==", 
"product_id"=>"1"} 

下面的代碼:

line_items_controller

def create 
    product = Product.find(params[:product_id]) 
    @line_item = @cart.add_product(product.id) 

    respond_to do |format| 
     if @line_item.save 
     format.html { redirect_to customer_cart_path } 
     format.json { render :show, status: :created, location: @line_item } 
     else 
     format.html { render :new } 
     format.json { render json: @line_item.errors, status: :unprocessable_entity } 
     end 
    end 
    end 

車型號:

class Cart < ActiveRecord::Base 
has_many :line_items, dependent: :destroy 
belongs_to :user 

def add_product(product_id) 
    current_item = line_items.find_by(product_id: product_id) 
    if current_item 
     current_item.quantity += 1 
    else 
     current_item = line_items.build(product_id: product_id) 
    end 
    current_item 
end 

def total_price 
    line_items.to_a.sum { |item| item.total_price } 
end 
end 

添加到購物車按鈕:

<%= button_to 'Add to Cart', line_items_path(product_id: product) %> 

先謝謝了!

+0

的'@ car'變量是'nil',它在哪裏定義? –

回答

0

在您的代碼:

def create 
product = Product.find(params[:product_id]) 
@line_item = @cart.add_product(product.id) 

線[3],採用@cart,但@cart之前它從未被設置成它不知道它是在該點什麼。

所以你需要在使用之前設置@cart。例如:

@cart = Cart.find(params[:cart_id]

此外,您將需要更新的代碼:

<%= button_to 'Add to Cart', line_items_path(product_id: product) %> 

到(如果你的cart對象存在於此):

<%= button_to 'Add to Cart', line_items_path(product_id: product, cart_id: cart) %> 
+0

感謝您的回答 - '<%=呈現部分:「line_items/line_item」,集合:(at)cart.line_items%>' - 此行在視圖中引發錯誤。錯誤是: 未定義的方法'line_items'爲零:NilClass –

+0

這意味着@ cart對象再次未設置。我現在假設,我們在控制器中的SHOW動作或類似的東西。因此,在控制器中定義該動作時,請設置@ cart –

+0

的值再次感謝您的回答。你是對的,但我在演出中有這樣的動作|| 一流的客戶:: CartsController

1

您尚未在LineItemsControllercreate方法中定義您的@cart實例變量並訪問其add_product方法。

@line_item = @cart.add_product(product.id) # <== HERE 
+0

認爲這是'add_product'是零? –

相關問題