Filtering Routes

This is a premium course, which you can purchase below.

Buy Now

Controllers have a set of hooks, if you will, called filters. You can run code before, after, or both.


Filters are used to run methods before or after a controller action is fired. Sometimes both, using around. The scaffold uses the before filter to set the resource instance for the routes that need it, and you can also use filters to ensure that users are authorized for a given route.
A good place to put this logic is in the base controller, our application_controller:

class ApplicationController < ActionController::Base

  def is_admin!
    redirect_to root_path unless user_signed_in? && current_user.is_admin?
  end

end

Make sure there's a redirect on this logic! It's tempting to return true or false, but that won't work for our needs.