I'd like to verify if the user is logged in on every single request to the server.
Something like:
:before_filter verify_logged_in
Where should I put that before_filter so it applies to all controller actions and all requests?
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. Example: class UserController < ApplicationController.
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.
Routing decides which controller receives which requests. Often, there is more than one route to each controller, and different routes can be served by different actions. Each action's purpose is to collect information to provide it to a view.
To ensure that filters apply to all actions, place it in the application_controller.rb.
Application Controller is the base class of all other classes.
If you put any filter in this class then the flow works as follows:
If you hit url say of users
resource with any action say index
action then:
The control first goes to Application Controller
. There it checks for filters, if finds any then it executes the filter method and after that it goes to index action of users controller.
Application Controller:
class ApplicationController < ActionController::Base
protect_from_forgery
before_filter :verify_logged_in
end
Other Controller:
class UsersController < ApplicationController
def index
end
Here in the above code you see that the other controller is inheriting the contents of parent controller which is application controller. So if you put before_filter
in the application controller then for every user it will verify if the user is logged in for each request.
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