Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. (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. Also, I would like to avoid global variables.

Any help would be much appreciated. Thanks! :)

like image 933
jim Avatar asked Jun 05 '10 05:06

jim


2 Answers

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.

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

like image 123
Christos Avatar answered Oct 16 '22 14:10

Christos


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:

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

On Rails 4 and 5 before_filter it's deprecated. You can use this instead:

before_action :set_admin, except: [:create, :update, :destroy]

like image 16
Uģis Ozols Avatar answered Oct 16 '22 13:10

Uģis Ozols