I have a rails 4.2.x app, with devise for authentication - I have several controllers.
I want the devise authenticate_user! method to be run on all controllers and actions except on the home controller index action. (Of course, authenticate_user! itself takes care that devise actions like login go through)
I can ensure that every controller action runs the before_action in application_controller.rb:
class ApplicationController < ActionController::Base
before_action :authenticate_user!
...
end
I can also restrict a specific set of actions on all controllers:
class ApplicationController < ActionController::Base
before_action :authenticate_user!, except: [:index]
...
end
But I don't see how to make just home/index to be an exception.
I could, of course, manually add before_action :authenticate_user!
to every controller, and add an exception to the home controller for the index action. But this is not very dry, and if I add new controllers, I need to remember to add this before_action to each of them.
What you have to do is to set autheticate_user! on all controllers like that :
class ApplicationController < ActionController::Base
before_action :authenticate_user!
...
end
And then on your HomeController you do that :
class HomeController < ApplicationController
skip_before_action :authenticate_user!, only: [:index]
...
end
Hope this will help you !
You can use params[:controller] to detect controller name of request.
class ApplicationController < ActionController::Base
before_action :authenticate_user!
AUTHENTICATE_USER_EXCEPT_CONTROLLERS = ['controller_names_you_want_to_exclude']
...
def authenticate_user!
unless AUTHENTICATE_USER_EXCEPT_CONTROLLERS.include?(params[:controller])
super
end
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With