I have been baffled by this for a while?
I have been going through some tutorials and got stuck on this.
The following gives me an error in the view “You have a nil object
when you didn’t expect it” for “display_cart”. It’s saying the
variable “@items” is nil in the view.
But if i reorder the functions and put “display_cart” before
“find_cart”, it works.
Does the order of the functions matter?
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
private
def find_cart
session[:cart] ||= Cart.new
end
def display_cart
@cart = find_cart
@items = @cart.items
end
end
Hi –
On Sat, 4 Aug 2007, … wrote:
I have been baffled by this for a while?
I have been going through some tutorials and got stuck on this.
The following gives me an error in the view “You have a nil object
when you didn’t expect it” for “display_cart”. It’s saying the
variable “@items” is nil in the view.
But if i reorder the functions and put “display_cart” before
“find_cart”, it works.
Does the order of the functions matter?
No, but their relation to the “private” directive does. If
display_cart is private, then the action won’t be executed; instead,
the template will be rendered directly, and since the action was
skipped, @items won’t be set.
So you’ll need to move display_cart above “private”, or declare it
public. (I’d move it; it gets messy if you start declaring access for
methods individually.)
David
–