I have lots of controller in my Rails application, and I need to use a before_filter
before some actions in different controllers. The before filter will execute the same code of all these actions. Is there a clean DRY way(in application_controller
for instance) to specify the list of actions that should run this before_filter
? I have tried to use before_filer
in all controllers(9), but this looks so repetitive since it is the same code.
Asked
Active
Viewed 276 times
0

anyavacy
- 1,618
- 5
- 21
- 43
-
Did you check this question? http://stackoverflow.com/questions/6011764/specify-which-controllers-to-exclude-from-before-filter – Kapitula Alexey Aug 31 '16 at 11:46
-
thnks but it does not answer my question. – anyavacy Aug 31 '16 at 11:50
1 Answers
1
why not ApplicationController
? If you define any before_filter
in application controller then it is going to be executed on each request.
Now you are saying it looks repetitive but it actually don't. mentioning before_filter
in application_controller.rb
actually represents DRY AKA you don't have to specify that before_filter
anywhere else.
Of course not all of the 9 controllers are going to get execute at the same time so ApplicationController
is a preferred way
class ApplicationController < ActionController::Base
...
before_filter :pre_execute_action
...
end
class MyController < ApplicationController
...
skip_before_filter :pre_execute_action, except: [:methods_for_which_it_should_execute]
...
end
try above code as a reference

Rajdeep Singh
- 17,621
- 6
- 53
- 78

Kushal
- 342
- 1
- 7
-
the problem is that if I put it in application_controller it will be execute before ALL action. and I want it to be execute only for about 20% of the actions not ALL of them. I have about 70 actions and I want the before_filter to be executed before only 12 actions – anyavacy Aug 31 '16 at 11:52
-
so for that you can have `skip_before_filter :method_defined_in_application_controller except: [:methods_for_which_it_should_execute]` now it will run for only those 20% of actions. you have to define this in the controllers where you need it to execute for certain methods – Kushal Aug 31 '16 at 11:55