Hi everybody,
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):
1:
Display Cart
2:
3:
4: Your cart contains <%= @items.size %> items.
5:
<— end error here —>
Here is a copy/paste of my code:
<— file store_controller.rb begin here —>
class StoreController < ApplicationController
def index
@products = Product.salable_items
end
def add_to_cart
product = Product.find(params[:id])
@cart = find_cart
@cart.add_product(product)
redirect_to(:action => ‘display_cart’)
end
def diplay_cart
@cart = find_cart
@items = @cart.items
end
private
def find_cart
session[:cart] ||= Cart.new
end
end
<— file store_controller.rb end here —>
<— file application.rb begin here —>
class ApplicationController < ActionController::Base
model :cart
model :line_item
end
<— file application.rb end here —>
<— file cart.rb begin here —>
class Cart
attr_reader :items
attr_reader :total_price
def initialize
@items = []
@total_price = 0.0
end
def add_product(product)
@items << LineItem.for_product(product)
@total_price += product.price
end
end
<— file cart.rb end here —>
<— file line_item.rb begin here —>
class LineItem < ActiveRecord::Base
belongs_to :product
def self.for_product(product)
item = self.new
item.quantity = 1
item.product = product
item.unit_price = product.price
item
end
end
<— file line_item.rb end here —>
<— file display_cart.rhtml begin here —>
Display Cart
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
tried Firefox) - Delete all the cookies
- Check for typos
- Restart WEBrick
- Reboot my computer (I’m using Windows XP with mySQL 5.0.18 and RoR
1.2)
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.