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:
- <%= h(product.title) %>
4: <% for product in @cart.items %>
5:
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