How To Implement Filter On Controller Actions In Rails

What exactly filter is ? Filter is a simple method which is executed “before” / “after” / “around” a controller action.

For example, one filter might check if the user has the credentials for accessing a particular action in a controller.

Where can I place my  filter ?

Filters are inherited so if you  a place filter in “application_controll.rb” file then it will be applicable to every controllers in application.

Step – 1
Create a method ( in application_controller.rb file) :

def check_user_logged_in
 
            if !session[:username]
   
 flash[:notice] = "Sorry, login before you continue !!! "
 redirect_to :controller => "user_sessions", :action => "new"
      end
  end

Step – 2

Use the method in application_controller as a filter  :

Now write the before_filter block in the controller  where you want to restrict unauthorized users.
You can also restrict particular action of a controller by writing the action name.

class UsersController < ApplicationController #as controller is inherited from ApplicationController hence filter is accessible here.

before_filter :check_user_login_in, :only => [:profile]
  #this line is important
 
       def profile
         [ Your block of code to render your profile page ]
        end
  end

In the above block the “before_filter” restrict the non-registered user to access the profile page and redirect them to login page.
We can also restrict multiple actions by writing like this :

before_filter :user_logged_in, :only => [:profile, :edit]

In this case the filter is applied to only these two methods of a particular controller :

before_filter :user_logged_in, :except => [:index, :show]

in this case filter is applied to all the other actions except index and show action of a particular controller.
if a filtration action fails then respective controller action won’t get exectued and the further scheduled  filters are also get cancelled.

150 150 Burnignorance | Where Minds Meet And Sparks Fly!