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
]
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With