I’ve search a lot on google to help me with this one without success. I
know that some people had the same problem as I have, but there
solutions doesn’t seems to work for me.
I’m trying to do the depot example in the AWDwR book. But now I’m stock
with a problem that I can’t solve. I get this error:
<— begin error here —>
NoMethodError in Store#display_cart
Showing app/views/store/display_cart.rhtml where line #4 raised:
You have a nil object when you didn’t expect it!
You might have expected an instance of Array.
The error occured while evaluating nil.size
Extracted source (around line #4):
4: Your cart contains <%= @items.size %> items.
<— end error here —>
Here is a copy/paste of my code:
<— file store_controller.rb begin here —>
class StoreController < ApplicationController
@products = Product.salable_items
product = Product.find(params[:id])
@cart = find_cart
redirect_to(:action => ‘display_cart’)
@cart = find_cart
@items = @cart.items
session[:cart] ||= Cart.new
<— file store_controller.rb end here —>
<— file application.rb begin here —>
class ApplicationController < ActionController::Base
<— file application.rb end here —>
<— file cart.rb begin here —>
def initialize @items =  @total_price = 0.0 end def add_product(product) @items << LineItem.for_product(product) @total_price += product.price end
<— file cart.rb end here —>
<— file line_item.rb begin here —>
class LineItem < ActiveRecord::Base
def self.for_product(product) item = self.new item.quantity = 1 item.product = product item.unit_price = product.price item end
<— file line_item.rb end here —>
<— file display_cart.rhtml begin here —>
Your cart contains <%= @items.size %> items.<--- file display_cart.rhtml end here --->
Here is what I tried so far:
- Delete all the cache from my browser (I’m using Opera, but I also
- Delete all the cookies
- Check for typos
- Restart WEBrick
- Reboot my computer (I’m using Windows XP with mySQL 5.0.18 and RoR
I have put some breakpoint() in my code. The ‘Cart’ is created, @items
is set correctly and the session is also working (inside
store_controller.rb). If I put a breakpoint() method inside the
‘display_cart.rhtml’, at the prompt, I can see that the 'session[:cart]
variable is properly set, but the ‘@items’ is set to ‘nil’. It really
seems like the ‘@items’ is not readable or not set from within the
‘display_cart.rhtml’ file. But I think that the ‘:model cart’ line is
correctly set in my ‘application.rb’.
Can somebody help me with this one?
Thanks a lot.