Alex W. wrote:
So the only reason to use an instance variable is if you
want the view aware of that variable.
So like he said above.
Of course you want your instance @row in the view if its a database row.
Otherwise there is nothing to view.
But vars for counters in loops or whatever don’t have to be instances of
But maybe I am wrong.
I say again, regarding controllers:
Instance Variables: Passed to views.
Local Variables: Not passed to views.
class SomeController < …
post = Post.find(params[:id])
post.user = User.find(params[:user_id])
redirect_to :action => 'index'
So in the above example there are no instance variable because there is
no view, therefore since nothing needs to be passed along, all variables
should be local.
That’s mostly right. You might want an instvar in your controller to
help refactor your methods or simplify control flow. A typical example
is using a before filter to set up state that is needed by all actions
and stash that in an instvar for the actions to use. User authentication
systems commonly use that pattern.
And of course model objects can have their own instvars too. They can be
handy for holding values that are never stored in the database. For
example, you can create a “password” instvar to hold the plaintext
password that is entered on a form, then convert it to a MD5 hash value
to store it in the “hashed_password” field in the database.
My rule of thumb is that if the value is only needed within a method, it
should be a local. If other methods in the object (or a controller’s
view) need the value, make it an instance variable.