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

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


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  endend