Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a before_action to run on all controllers and actions except one?

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.

like image 979
Anand Avatar asked Mar 30 '16 07:03

Anand


2 Answers

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 !

like image 143
I'm_ADR Avatar answered Nov 19 '22 15:11

I'm_ADR


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
like image 20
Tri M Bui Avatar answered Nov 19 '22 15:11

Tri M Bui