What is the Importance of Filters in Rails

What is the Importance of Filters in Rails

Rails

In Ruby on Rails development, filters play a vital role. They are the methods 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.

If you write the before_filter block in the “ApplicationController” then the
filter will be applied to all the controllers.

Planning anything on Ruby on Rails? Talk to Andolasoft’s experts to get a clearer idea.

Leave a Reply