Skip_before_action for multiple controllers in Rails?

Hi, I am creating an api section for an application. My all API-related controllers are inside the app/controllers/api directory.

I am worried that there is a filter before_action :authenticate_user! in application_controller before_action :authenticate_user! so I have to be in login mode in order to access the api.

My current solution: I add skip_before_action :authenticate_user! to all controllers that are in app/controllers/api .

Problem: I have to write in all controllers, and I have about 80 controllers

My expectation: Is there a way in which I can write to application_controller , something like this before_action: authenticate_user !, except: [ all the controllers which are in api directory ]

+6
source share
2 answers

You can try it like this if all the controllers are in the API folder:

 class ApplicationController < ActionController::Base before_action :authenticate! def authenticate! if params[:controller].split("/").first == "api" return true # or put code for what wherever authenticate you use for api else authenticate_user! end end end 
+2
source

You need to specify skip_before_action :authenticate_user! in each controller whose actions do not need to be authenticated. You cannot pass a controller name or any thing like this as an argument to the skip_before_action method.

One solution: you can create a controller called APIController , and you can specify skip_before_action there:

 class APIController < ApplicationController skip_before_action :authenticate_user! # rest of the code end 

And then all the controllers in app/controllers/api/ can inherit from APIController .

 class OtherController < APIController end 
+17
source

All Articles