views:

47

answers:

3

i am creating a simple shopping cart in rails, when I add the product to cart i get this error : You have a nil object when you didn't expect it!

the add to cart method is :

  def add_to_cart  
    begin
      product = Product.find(params[:id])
    rescue ActiveRecord::RecordNotFound
      logger.error("Attemp to access invalid product #{params[:id]}")
      flash[:notice] = "Invalid Product !"
      redirect_to :action => :index
    else
      @cart = find_cart     
      @cart.add_product(product)
    end
  end

and the add_product in cart :

  def add_product(product)
    current_item = @items.find {|item| item.product == product}
    if current_item
      current_item.increment_quantity
    else
      @items << CartItem.new(product)
    end    
  end

the cart was working properly, when I add the rescue method to add_to_cart this happened...

A: 

Maybe the begin starts a new scope so that the product var is local to it. And when you then add the product in the rescue block it is a new local with Nil.

To test this theory just add a product = nil before the whole begin, rescue block of code

nasmorn
It's either that, or @cart is nil because the find_cart method found nil. Between those two suggestions you should be able to figure it out. Ruby debugger might help: http://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-ruby-debug
hgimenez
A: 

I'm going to guess that it's not a scope issue, as the following irb test demonstrates:

irb(main):001:0> begin
irb(main):002:1* product = 'abc'
irb(main):003:1> rescue Exception => ex
irb(main):004:1> nil
irb(main):005:1> else
irb(main):006:1* puts product.inspect
irb(main):007:1> end

The best way to figure this out, IMO, is to find out what's in product immediately after the find using a LOGGER.debug "product now contains #{product.inspect}".

Your backtrace will be informational as well. At this point, it's tough to say what the interpreter is complaining about. It could be that product is nil, but just as easily, it could be @cart or something referenced in your view.

Steve Ross
A: 

How is @items in your add_product method defined? I can't see it anywhere, is it that?

tsdbrown