small medium large xlarge

Generic-user-small
03 Aug 2008, 01:32
Max Norman (17 posts)

When I try to add something to my cart, I get 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.«

app/models/cart.rb:9:in add_product' app/controllers/store_controller.rb:10:in add_to_cart’

What exactly is the problem?

Samr_small_pragsmall
03 Aug 2008, 03:10
Sam Ruby (634 posts)

Make sure that cart.rb looks exactly like “this”:http://media.pragprog.com/titles/rails3/code/depot_f/app/models/cart.rb

Line 9 is

@items << product

The message indicates that @items has not been initialized. This should have been done on line 5:

@items = []

Check both lines, for spelling mistakes, missing @ signs or the like.

Generic-user-small
03 Aug 2008, 03:16
Max Norman (17 posts)

Thank you for responding, Mr. Ruby. It is very comforting as a reader to know that you are so available and outgoing.

I can’t find and errors with my cart.rb. I’ve pasted it up here:

@code font@ class Cart attr_reader :items

def initialize
	@items = []
end

def add_product(product)
	@items << product
end end @code font@
Samr_small_pragsmall
03 Aug 2008, 11:36
Sam Ruby (634 posts)

That code appears to be correct. My next guess is that somehow you created a Cart without setting @items correctly, and then subsequently fixed the code, but the original Cart is still captured and stored in your session.

Try

rake db:sessions:clear
Generic-user-small
03 Aug 2008, 16:53
Max Norman (17 posts)

It worked! Thank you!

Generic-user-small
03 Dec 2008, 14:19
Michael Tobola (2 posts)

Hi, I am getting the same error as Max except rake db:sessions:clear isn’t fixing it. I have tried clearing the browser cache, restarting the server and clearing sessions but I still have problems. Is there anything beside cart.rb that could be causing these problems? I have triple checked that cart.rb is not the problem and copy-pasted the code you provided above but nothing is working. Thanks for any help.

You must be logged in to comment