What is the Importance of Filters in Rails

What is the Importance of Filters in Rails
Social sharing

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.

Summary
Article Name
Importance of Filters in Rails
Description
Filters are inherited, so if you set a filter on ‘ApplicationController’, it would run on every controller in your application.
Author
Publisher Name
Andolasoft
Publisher Logo

Your recently viewed posts:

    Contact Us

    We’d love to help & work with you




    When do you want to start ?


    Enter your email address to stay up to date with the latest news.
    Holler Box

    Orange Exit pop up

    Subscribe for the latest
    trends in web and
    mobile app development
    Holler Box

    Exit pop up

    Sad to see you leaving early...

    From "Aha" to "Oh shit" we are sharing everything on our journey.
    Enter your email address to stay up to date with the latest news.
    Holler Box