简体   繁体   English

Rails在所有控制器操作中变量

[英]Rails Variable across all controller actions

This should be a very simple rails question. 这应该是一个非常简单的轨道问题。 I have a variable like the following. 我有一个如下变量。

@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. 我希望通过我所有控制器上的每个控制器操作都可以访问这个变量,例如,如果我有一个Product控制器,并且在其中我有通常的CRUD操作,我希望将上面定义的@administration变量放入所有CRUD行动。 (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. 我的项目中有很多控制器,我想知道是否有一种比通过我想要的所有操作手动添加它更简单的方法。

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. 但是当我更新Administration.first表的实际内容时,我遇到了一个没有更新的问题。 Also, I would like to avoid global variables. 另外,我想避免全局变量。

Any help would be much appreciated. 任何帮助将非常感激。 Thanks! 谢谢! :) :)

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

Just extending Christos post... 只是扩展Christos帖子......

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 to before_filter,如下所示:

before_filter :set_admin, :except => [:create, :update, :destroy]

On Rails 4 and 5 before_filter it's deprecated. 在Rails 4和5之前,before_filter它已被弃用。 You can use this instead: 您可以使用此代替:

before_action :set_admin, except: [:create, :update, :destroy] before_action:set_admin,但:[:create,:update,:destroy]除外

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

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