简体   繁体   中英

Ruby on Rails rendering access to instance variables

当我渲染部分视图或渲染未直接映射到控制器的视图时,该其他视图是否可以访问控制器的实例变量?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM