An instance variable will be available to embedded ruby calls in your
rhtml templates; a local variable will only be available within the
it’s defined in.
In the example from AWDWR you quoted:
@cart = find_cart
product = Product.find(params[:id])
@cart is an instance variable (denoted with an @ symbol), because it’s
instance of the Cart object. Product is a local variable, its scope is
local to the action (method) add_to_cart. @cart can be exposed in web
pages, but product cannot.
Further down AWDWR shows the instance variable @cart exposed in the
Your Pragmatic Cart
<% for item in @cart.items %>
- <%= item.title %>
<% end %>
The rule of thumb is: to make data visible to your user, use an instance
variable. The AWDWR book does a much better job of illustrating these
Hope this helps!
Information and Educational Technology
Kwantlen University College - 604-599-2120
“So powerful is the light of unity that it can illuminate the whole
Kristen [email protected]
Sent by: [email protected]
02/03/2007 06:14 PM
Please respond to
[Rails] Re: Trying to understand something about instance variables.
- Next, a Product object is created as a result of a find from the
database using an id parameter from the request. It’s only a local
variable and it’s called product.
- The product is added to the @cart.
Hmm, Im kinda getting the idea now, but could you clarify the difference
between an instance variable and a local variable. How do I know when I
should use an instance or a local variable. Is there a rule of thumb?
Thanks you for your replies so far.
Posted via http://www.ruby-forum.com/.