Dear all,
I'm going, by the book, through the book "Agile Web Development 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: <h1> Your Pragmatic Cart</h1>
3: <ul>
4: <% for product in @cart.items %>
5: <li><%= h(product.title) %></li>
6: <% end %>
7: </ul>
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
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---