Importance of Filters in Rails by Jay December 13, 2012 2 Minutes ReadIn 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 controllerStep#1In 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 endStep#2Now 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 thisbefore_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.Related Posts: Usage of PDFKit with Rails 3.2.8 and Ruby 1.9.3 File uploading through Paperclip in rails 3.x Ruby Rails Development Sphere & Associated MythsTags: Rails, Rails App, RoR Jayadev Das email@example.comDo what you do best in – that’s what I’ve always believed in and that’s what I preach. Over the past 25+ years (yup that’s my expertise ‘n’ experience in the Information Technology domain), I’ve been consulting to small, medium and large companies ‘bout Web Technologies, Mobile Future as well as on the good-and-bad of tech. Blogger, International Business Advisor, Web Technology Expert, Sales Guru, Startup Mentor, Insurance Sales Portal Expert & a Tennis Player. And top of all – a complete family man!