简体   繁体   English

Ruby on Rails呈现对实例变量的访问

[英]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. 实际上,您不会直接访问控制器动作中存在的控制器实例变量,而发生的是Rails克隆它们并将它们传递给视图。 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. 是的,Rails允许多个视图共享控制器中定义的实例变量。 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? ): 根据本文中的Ryan Bates,以下是使用渲染访问实例变量的准则( Rails:局部对象是否应该知道实例变量? ):

  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 %>. 如果partial与资源名称相同,则使用<%= render @item%>将其作为本地传递。

  3. If the partial will be shared across multiple controllers then only use locals. 如果部分内容将在多个控制器之间共享,则仅使用本地。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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