NoMethodError in Store#add_to_cart

Dear all,

I’m going, by the book, through the book “Agile Web D. with
Rails, 2nd edition”. I get stuck in section 8.2

I am running into following error:

NoMethodError in Store#add_to_cart

Showing app/views/store/add_to_cart.html.erb where line #4 raised:

You have a nil object when you didn’t expect it!
The error occurred while evaluating nil.items

Extracted source (around line #4):

1:
2:

Your Pragmatic Cart


3:

    4: <% for product in @cart.items %>
    5:
  • <%= h(product.title) %>

  • 6: <% end %>
    7:

RAILS_ROOT: /home/gaoxh04/rails/depot

The following is the ruby code:
app/controllers/store_controller.rb

class StoreController < ApplicationController

def index
@products = Product.find_products_for_sale
end

private
def find_cart
session[:cart] ||= Cart.new
end

def add_to_cart
@cart = Cart.new
product = Product.find(params[:id])
@cart.add_product(product)
end

end

app/models/cart.rb

class Cart
attr_reader :items

def initialize
@items = []
end

def add_product(product)
@items << product
end
end

Kind regards,
Xiahong

On Jun 17, 10:51 pm, Xiahong G. [email protected] wrote:

end

def add_to_cart
@cart = Cart.new
product = Product.find(params[:id])
@cart.add_product(product)
end

You’ve made your add_to_cart action private which it shouldn’t be
( rails ignores private methods when looking for actions, so it has
just rendered the template without running your add_to_cart method at
all.

Fred

Oh, I didn’t notice that… thanks a lot … I appreciate it.

2009/6/18 Frederick C. [email protected]