Importance of filter in rails
- 1. Importance of Filter in Rails
In Ruby on Rails development filters play a vital role. Filters are the methods that are
executed ‘before’, ‘after’ or ‘around’ a controller action. For example, one filter might
check to see if the user has the credentials to access that particular controller or action.
Filters are inherited, so if you set a filter on ‘ApplicationController’, it would run on every
controller in your application.
Below is an example to explain how a filter can be used to restrict a non-logged in user
to access specified actions in a controller.
Step#1
In Application controller write the following block of code according to the requirement.
def user_login_required
if !session[:username]
flash[:notice] = "Oops you need to login!"
redirect_to :controller => "user_sessions", :action => "new"
end
end
Step#2
Now write the before_filter block in the controller you want to restrict the not registered
users. You can also restrict particular actions of a controller by writing the action name.
class UsersController < ApplicationController
before_filter :user_login_required, :only => [:profile]
def profile
[Your code block goes here]
end
end
In the above block the ‘before_filter’ restrict the not 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_login_required, :only => [:profile,:edit]
In this case the filter is applied to only these two methods of a particular controller.
before_filter :user_login_required, :except => [:index,:show]
In this case the filter is applied to all other actions except index and show action of a
particular controller.
- 2. If you write the before_filter block in the “ApplicationController” then the filter will be
applied to all the controllers.