Rails_learner Rails_learner - 7 months ago 34
Ruby Question

Rails Error: Undefined method `add_product' for nil:NilClass

I'm quite new to Rails so might be a stupid mistake i'm making and just need someone to point it out.

Building a small shopping cart app. When i click 'Add to Cart', it throws up this error:

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


Parameters:

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


Here's the 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


Cart Model:

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


Add to Cart Button:

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


Thanks in Advance!

Answer

In your code:

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

line [3], uses @cart, but @cart was never set before it so it doesnt know what it is at that point.

So you need to set @cart before using it. Ex:

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

Also, you will need to update the code:

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

to (if your cart object exists here):

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