2017-02-15 3 views
-3
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 

私はエラー(第三)ライン、それが言う**未定義のメソッド` +を得ました'何が間違っている:| **未定義のメソッド `+私は見当がつかないNilClass :nilのための 'ゼロのためNilClass(current_item.quantity + = 1)

class Cart < ApplicationRecord 

has_many :line_items, dependent: :destroy 


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 

**And my line_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 @line_item.cart, notice: 'Line item was successfully created.' } 
     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 


def change 
    add_column :line_items, :quantity, :integer, default: 1 
end 
+2

"何が間違っているのか分かりません" - エラーがあなたに伝えます。 'current_item.quantity'はnilです。 –

答えて

-1

正確に量をチェックしますか?それが1より大きい場合は? A + = BはA = A + Bであるため、演算子がそのように動作するかどうかはわかりませんが、nilクラスのエラーが発生するため、current_itemはゼロに見えます。 current_itemがレールで見つかっていることを確認してください。または数量はゼロです。 @Icemanはあなたの質問にすでに答えているのを見ました。

paramsにproduct_idを渡し、コントローラにfind_by(:product_id)があることを確認してください。 current_itemを取得したときにnilでなければ、数量がnilであるかどうかを確認するだけです。いくつかの数量がゼロの場合、ifとloopを使ってエラーをエスケープするかもしれません。例えば。何もしない場合など

0

byebugを使用して、quantityが存在することを確認してください。 私は、そのソリューション

current_item = line_items.find_by(product_id: product_id) 

if current_item.present? 
    current_item.quantity += 1 unless current_item.quantity.nil? 
else 
    current_item = line_items.build(product_id: product_id) 
end 
current_item 
0

代わりcurrent_item.quantity += 1 =>current_item.increment(:quantity)、今それが動作を提案することができます。

関連する問題