I am new to Rails, and I was trying to follow the “Agile Web D.
With Rails” textbook. As I was trying to create the “Add_to_cart”
application, I found that when I clicked the “Add to Cart” link on my
http://localhost:3000/store page, I got the following error:
NoMethodError in Store#display_cart
Showing app/views/store/display_cart.rhtml where line #20 raised: You
a nil object when you didn’t expect it!
The error occurred while evaluating nil.product
Extracted source (around line #20): 17:
19: for item in @items
20: product = item.product
Just for pointer, I had actually got to the correct page once, but then
skipped the “Iteration C2: Handling Errors” part in the tutorial and
straight to the “8.5 Iteration C3: Finishing the Cart” part, and
the empty_cart function there. I have been getting this problem since
(when I implemented this function and clicked the link in browser and
came back to add more objects to the cart). Could it be that I have
the object or something? After some googling I thought that the problem
actually related to the session, and so i tried to clear the session by
- rake db:sessions:clear
- rake tmp:sessions:clear
But even this did not solve the problem. So I am clueless as of now.
is the code for reference:
def add_to_cart product = Product.find(params[:id]) @cart = find_cart @cart.add_product(product) redirect_to(:action => 'display_cart') end def display_cart @cart = find_cart @items = @cart.items if @items.empty? redirect_to_index("Your cart is currently empty") end end def find_cart session[:cart] ||= Cart.new end
Any help would be really appreciated !!!