Ruby-on-rails – How to make a before_action to run on all controllers and actions except one

callbackdeviseruby-on-rails

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.

Best Solution

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 !

Related Question