0

When I render a partial or I render a view that is not directly mapped to my controller, does this other view have access to controller's instance variables?

mary
  • 869
  • 5
  • 13
  • 26

2 Answers2

0

In fact you don't access your controller's instance variables present in the controller actions directly, what happens is that rails clones them and passes them to the view. You then can access their values through these clones.

You can only access these cloned variables in the correspondent view of your controller action during the request. However, your application has a session for each user in which you can store small amounts of data that will be persisted between requests.

Luís Ramalho
  • 10,018
  • 4
  • 52
  • 67
  • so this is true for both cases? both the rendering of partial templates and rendering the regular template? – mary Jul 10 '13 at 11:29
  • A partial doesn't have a controller associated with it, thus you need to pass the variable explicitly. Like so `render 'some_partial', :variable => @variable` – Luís Ramalho Jul 10 '13 at 12:52
  • I'm not sure about it, please look at part: 7.2 Rendering a Partial Form of http://edgeguides.rubyonrails.org/getting_started.html , you will see that the partial example does access "@"post. what is the meaning of render "@"post.comment in this context? – mary Jul 11 '13 at 06:59
  • Yes, sorry my comment wasn't clear. What I meant to say was that a partial doesn't have a direct controller associated, it basically gets the variable of the controller associated with the view where you render it. So in that case you mentioned it will get the variable from the `CommentsController#create` -- however if you update the record, then it will assume the variable of the `edit` action. – Luís Ramalho Jul 11 '13 at 08:44
0

Yes, Rails allows multiple views to share instance variable defined in controller. However, you should avoid sharing instance variable across multiple views this is because instance variable may be changed inside the view and not have the original value that's intended to be displayed in the next view.

Below is the guidelines in accessing instance variable with rendering according to Ryan Bates in this post (Rails: Should partials be aware of instance variables?):

  1. Never create an instance variable just to share it between partials. Usually this means you will only be sharing the controller resource object.

  2. If the partial is the same name as the resource, pass it as a local with <%= render @item %>.

  3. If the partial will be shared across multiple controllers then only use locals.

Community
  • 1
  • 1
Antonio Jha
  • 1,301
  • 13
  • 13