Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply before_filter to every action of every controller in Rails 3.2.11?

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?

like image 274
sergserg Avatar asked Feb 07 '13 13:02

sergserg


People also ask

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. Example: class UserController < ApplicationController.

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.

What decides which controller receives which requests in Rails?

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.


2 Answers

To ensure that filters apply to all actions, place it in the application_controller.rb.

like image 186
David Hahn Avatar answered Sep 28 '22 04:09

David Hahn


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.

like image 35
My God Avatar answered Sep 28 '22 05:09

My God