简体   繁体   中英

Rails Error: undefined method ` ' for nil:NilClass

So, since I'm fairly new to rails (and ruby), I'm still trying to understand where it all goes wrong here. I'm working on a cart in a webshop. The user gets a Session where his cart items (In this case line_item.rb) is stored.

Problem: When I click an item, it gets added to the cart via the cart method add_product. If you click on the same item again, instead of adding the same item twice, it should simply then ++1 to the quantity-property of that item. But, when I click it the second time i get the error page saying:

NoMethodError in LineItemsController#create

undefined method `+' for nil:NilClass

Here is my cart.rb:

class Cart < ActiveRecord::Base
  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
      Rails.logger.debug(current_item.quantity)
    else
      current_item = line_items.build(:product_id => product_id)
    end
    current_item
  end
end

The quantity property for line_item is of type integer. Should be able to add integers to it, right? Thats where I'm confused at the moment.

Here is the "create" method in line_items_controller.rb:

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

respond_to do |format|
  if @line_item.save
    format.html { redirect_to @line_item.cart,
      notice: 'Line item was successfully created.' }
    format.json { render json: @line_item,
      status: :created, location: @line_item }
  else
    format.html { render action: "new" }
    format.json { render json: @line_item.errors,
      status: :unprocessable_entity }
  end
end

end

Any Ideas?

Cheers

I think it's because current_item doesn't have any quantity. There's probably no default value. You're expecting it to be 0, but it's actually nil .

I set a default value, and make sure that column can't be nil. Also, you can define a before_create method that would set that value to 0 before saving (if it's nil).

Another way to fix this would be making sure you don't have a nil there:

current_item.quantity = current_item.quantity.blank? ? 1 : current_item.quantity + 1

This says that current_item.quantity is null. This can be Integer but stored as null in database. If this, you can set one value by default (in migration), or when you create for first time you can set the quantity value to 1.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM