Unexpected nil object
-
30-04-2021 - |
문제
I'm currently working on my project and I'm new in Ruby on Rails.
I'm working with cart to group same products in a single line item
and took me to this error:
You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.+
I can't understand why the method created cannot be found
line_item_controller.rb:
def create
@cart = current_cart
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.xml { render :xml => @line_item,
:status => :created, :location => @line_item }
else
format.html { render :action => "new" }
format.xml { render :xml => @line_item.errors,
:status => :unprocessable_entity }
end
end
end
The inside of the Cart
module:
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 view is cart show is
<% for item in @cart.line_items %>
<li><%= item.quantity %> × <%= item.product.title %></li>
<% end %>
EDIT:
I seriously I don't know what happen but when I type:
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
This line to be exact it went good in going
current_item.quantity += 1
May someone explain what just happened ?
해결책
Instead of current_item.quantity += 1
try current_item.quantity = current_item.quantity.to_i + 1
What I did is that if current_item.quantity
is nil
, current_item.quantity.to_i
will be = 0, else it will get the integer value of current_item.quantity
다른 팁
From given code, I suspect only following line current_item.quantity += 1
. I guess it is nil sometimes, that's why you are getting exception.
Make sure the quantity value is initialized to 1 properly when you do the following,
current_item = line_items.build(:product_id => product_id)
Note: When you look at the log, you can find out the line number where the exception is raised. Inspect the variable used in that line and dig more.