Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

skip_before_action for a few controllers in Rails?

Hi I'm building an api section for an app. My all api related controllers resides inside app/controllers/api directory.

My concern is that in application_controller there is a filter before_action :authenticate_user!, so I have to be in login mode to access the api.

My current solution: I'm adding skip_before_action :authenticate_user! in all the controllers which are in app/controllers/api directory..

Problem: I have to write in all the controllers and I have around 80 controllers

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

like image 722
ashwintastic Avatar asked Apr 27 '16 07:04

ashwintastic


People also ask

What is controller callback in rails?

Abstract Controller Callbacks Abstract Controller provides hooks during the life cycle of a controller action. Callbacks allow you to trigger logic during this cycle. Available callbacks are: after_action. append_after_action.

What is the role of rails controller?

The Rails controller is the logical center of your application. It coordinates the interaction between the user, the views, and the model. The controller is also a home to a number of important ancillary services. It is responsible for routing external requests to internal actions.

What is Before_filter in Ruby on Rails?

Rails before filters are executed before the code in action controller is executed. The before filters are defined at the top of a controller class that calls them. To set it up, you need to call before_filter method.

What does Before_action do in Rails?

When writing controllers in Ruby on rails, using before_action (used to be called before_filter in earlier versions) is your bread-and-butter for structuring your business logic in a useful way. It's what you want to use to "prepare" the data necessary before the action executes.


1 Answers

You can try like this if all the controllers are under 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
like image 68
Thorin Avatar answered Sep 30 '22 15:09

Thorin