Rails Instance Variables in Controllers?
DiggBlinkRedditDeliciousTechnorati
question by Bejaan | Easy
Hello,
I have the following action in a controller
def edit
@apartment = Apartment.find(params[:id])
render :partial => 'full_edit_apartment', :locals => {:apartment
=> @apartment}
end
This code works just fine if the apartment variable is an instance
variable, but does not work if the apartment variable is not an
instance variable. My question is why?
It doesn't seem like I need an instance variable, since the
full_edit_partial only references a local variable called apartment and
not an instance variable.
- Bejaan
Post reply
Subscriptions
Re: Rails Instance Variables in Controllers?reply by Wasim It is more to the sequence of how things work
First controller executes then views execute, also being a MVC
framework, they do not share local variables, so it can be instance
variables or global variables which are available to both controller
and views
Regards ,
Wasim Riyazi
Post reply
Subscriptions
Re: Rails Instance Variables in Controllers?reply by Bejaan Hi,
Thanks for your response, but I still don't understand.
I know that the controller gets executed first and then the view gets
executed. I also know that instance variables in the controller are
passed to the views. You can also pass variables from the controller to
the view via the :locals parameter, which is what I am doing right now.
What I don't understand is why this only works some of the time. Most
of the time that I use the :locals parameter it works just fine. I can
pass information to the view using just local variables. In this
particular case, I can pass the information when I use an instance
variable to store the activerecord object but when I use a local
variable to store the activerecord object, it does not work.
This leads me to believe that I don't understand something about
instance variables or :locals paramater. What am I not understanding
here?
Post reply
Subscriptions
Re: Rails Instance Variables in Controllers?reply by MarkP Hello,
I'm also confused about this! If the object passed as a local variable exists as instance variable to the controller, then it will be available to the view /as a local variable/ in the view as expected.
If the instance variable is not referenced by anything in the controller, it is not available /even when passed as a local variable/ to the view.
I think this is because the local vars in the controller method are always disposed before the view runs - however if they in reference an instance variable then they are not disposed.
It depends what language you're most familiar with. From my C background I would try to explain what I mean by saying that you're passing the value of a pointer - what that pointer references either gets deleted or not, but the value of that pointer (a memory address) is still the same.
Post reply
Subscriptions
Got a Ruby Question?
Just Sign Up and ask the top Ruby experts!
|