2016-04-19 14 views
0

私はRailsの新機能ですので、私が作っている間違いかもしれません。Railsエラー:未定義のメソッド `add_product 'for nil:NilClass

小さなショッピングカートアプリを構築する。 i 'がカートに追加' をクリックすると、このエラーをスローします。

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

パラメータ:

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 

カートモデル::

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

ここでコードがあります

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'変数

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

また、あなたは、コードを更新する必要がありますそれはどこに定義されていますか? –

答えて

0

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

ラインは、[3]、@cartを使用していますが、それは、それはその時点では何か知っているdoes notのように、その前に@cart設定していませんでした。

@cartは、使用する前に設定する必要があります。例:

<%= 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

お返事ありがとうございます - '%% render partial: "line_items/line_item"、コレクション:(at)cart.line_items%>' - この行は、ビューにエラーを投げます。エラーは次のとおりです。 未定義のメソッド 'line_items' for nil:NilClass –

+0

これは、@ cartオブジェクトが再び設定されないことを意味します。私は今、コントローラーのSHOWアクションまたはそのようなものにいると仮定します。したがって、コントローラー内のアクションの定義では、@ cart –

+0

の値を設定してください。もう一度お返事ありがとうございます。あなたは正しいですが、私はショーアクションでこれを持っています|| クラスカスタマー:: CartsController

1

LineItemsControllercreateメソッドで@cartインスタンス変数を定義し、そのadd_productメソッドにアクセスしていません。あなたのコードで

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

それは 'add_product'だと思っていました。 –

関連する問題