0

I want to complete a cart part in a site. The first time i add items into the cart it is ok, but the second time with the same items i would get a error:

undefined method `+' for nil:NilClass

Extracted source (around line #19):

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  

What is wrong?

Thanks.

3 Answers 3

1

The quantity field is probably null in the database. Change the infringing line to something like:

current_item.quantity = current_item.quantity.to_i + 1
Sign up to request clarification or add additional context in comments.

Comments

1

nil.to_i returns 0

So use current_item.quantity = current_item.quantity.to_i + 1

1 Comment

current_item.quantity.to_i += 1 will return error if quantity value is nil.
1

Seems like current_item.quantity is nil.

Try to set default value with

...
if current_item
  current_item.quantity ||= 1 # sets to 1 if nil
  current_item.quantity += 1  
else
...

If you store quantity in database, then add to your migration like null: false, default: 1

Hope it helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.