Ich bin ziemlich neu in Rails, also könnte ein dummer Fehler sein, den ich mache und nur jemanden brauche, um darauf hinzuweisen.Rails Error: Undefinierte Methode `add_product 'für nil: NilClass
Aufbau einer kleinen Einkaufswagen App. Wenn ich auf 'In den Warenkorb', wirft er diesen Fehler auf:
NoMethodError in LineItemsController#create
undefined method `add_product' for nil:NilClass
Parameter:
{"authenticity_token"=>"uZ6zOfA237VBzt3Pz2tEBESzjv2pg+Vhx73DTolL8f76ANS80qiU6+wcN8Tvq/r+CSZvzxnkKll/ZJl2H2XePQ==",
"product_id"=>"1"}
Hier ist der Code:
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
Wagen Modell:
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
in der Warenkorb Button:
<%= button_to 'Add to Cart', line_items_path(product_id: product) %>
Vielen Dank im Voraus!
Die '@ car' Variable ist 'nil', wo ist es definiert? –