small medium large xlarge

25 Dec 2008, 19:46
Pierce Freeman (12 posts)

I have been fine through the book until Chapter 8, but this is where I am starting to get problems. I am running the latest stable version of Rails, Ruby, and pretty much everything related to it… and I get the following error when trying to run my cart “script”.

NoMethodError in StoreController#add_to_cart

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 have learned that it is some problem with “@cart.add_product(product)” as when I comment out this line it works.

Any help would be great.

EDIT: Never mind, I figured it out.

25 Dec 2008, 22:09
David John Porter (12 posts)

Hi Pierce,

Please do post back what the problem was - you never know it might help someone else in the future!

cheers Dave

25 Dec 2008, 22:19
Pierce Freeman (12 posts)

I’m pretty sure it was a mis-spelled function… A word of advice to anyone looking at this for help: Copy and paste the code from the website if something is wrong and see if it fixes the problem… Then look back at your code and see what’s different.

26 Dec 2008, 00:43
SC (15 posts)

The other trick which is useful is to look at the tracing of the method calls below your NoMethodError message. It’ll show which files and which lines within those files were called to evoke the problem.

19 Feb 2009, 20:03
Mohit Keswani (1 post)

Change the cart.rb file to the following. The problem is that there is no find method for an array in ruby 1.8.7 (did not check 1.9.1). This should resolve the error.

class Cart

attr_reader :items 

def initialize
	@items = []

def add_product(product)
    current_item = nil
    @items.each do |cartItem| 
    	if ==
    		current_item = cartItem
    if current_item
    	current_item =
	@items << current_item
    current_item # Return the current item so the controller 

def total_price
	@items.sum { |item| item.price }

def total_items
	@items.sum { |item| item.quantity }
You must be logged in to comment