Ruby-on-rails 跨所有控制器操作的 Rails 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2979327/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails Variable across all controller actions
提问by jim
This should be a very simple rails question. I have a variable like the following.
这应该是一个非常简单的 rails 问题。我有一个如下所示的变量。
@administration = Administration.first
I want this variable to be accessible through every controller action across all my controllers so for example if I have a Product controller and inside of it I have the usual CRUD actions, I want the @administration variable as defined above to be put into all the CRUD actions. (It would not be needed in destroy or create or update). I have many controllers throughout my project and I was wondering if there is an easier way than adding it manually through all of the actions that I want it in.
我希望可以通过所有控制器的每个控制器操作访问此变量,例如,如果我有一个 Product 控制器,并且在其中我有通常的 CRUD 操作,我希望将上面定义的 @administration 变量放入所有CRUD 操作。(在销毁或创建或更新中不需要它)。我的项目中有很多控制器,我想知道是否有比通过我想要的所有操作手动添加它更简单的方法。
I tried a global variable
我尝试了一个全局变量
$administration = Administration.first
but I run into an issue where it is not updated when I update the actual content of the Administration.first table. Also, I would like to avoid global variables.
但是我遇到了一个问题,当我更新 Administration.first 表的实际内容时它没有更新。另外,我想避免全局变量。
Any help would be much appreciated. Thanks! :)
任何帮助将非常感激。谢谢!:)
回答by Christos
You could add a before_filter to your ApplicationController that sets the administration variable before any action is called and you can limit it to only the actions you require.
您可以在 ApplicationController 中添加一个 before_filter,在调用任何操作之前设置管理变量,并且您可以将其限制为仅您需要的操作。
class ApplicationController < ActionController::Base
...
before_filter :set_admin
def set_admin
@administration = Administration.first
end
..
http://api.rubyonrails.org/v2.3.8/classes/ActionController/Filters/ClassMethods.html
http://api.rubyonrails.org/v2.3.8/classes/ActionController/Filters/ClassMethods.html
回答by U?is Ozols
Just extending Christos post...
只是延长克里斯托斯的职位......
If you don't want @administration to be accessible to destroy, create and update controller actions then add :except => :action to before_filter like this:
如果您不希望 @administration 可被访问以销毁、创建和更新控制器操作,则将 :except => :action 添加到 before_filter 中,如下所示:
before_filter :set_admin, :except => [:create, :update, :destroy]
before_filter :set_admin, :except => [:create, :update, :destroy]
On Rails 4 and 5 before_filter it's deprecated. You can use this instead:
在 Rails 4 和 5 before_filter 上,它已被弃用。您可以改用它:
before_action :set_admin, except: [:create, :update, :destroy]
before_action :set_admin, 除了: [:create, :update, :destroy]

