Wiki | RDocs | Screencast
CanCan is an authorization library for Ruby on Rails which restricts what resources a given user is allowed to access. All permissions are defined in a single location (the Ability
class) and not duplicated across controllers, views, and database queries.
In Rails 3, add this to your Gemfile.
gem "cancan"
In Rails 2, add this to your environment.rb file.
config.gem "cancan"
Alternatively, you can install it as a plugin.
rails plugin install git://github.com/ryanb/cancan.git
CanCan expects a current_user
method to exist in controllers. First, set up some authentication (such as Authlogic or Devise). See Changing Defaults if you need to customize this behavior.
Next, make an Ability
class. CanCan 1.5 includes a generator for this.
rails g cancan:ability
This is where the user permission will be defined. See the comments in models/ability.rb and Defining Abilities for details.
The current user’s permissions can then be checked using the can?
and cannot?
methods in the view and controller.
<% if can? :update, @article %> <%= link_to "Edit", edit_article_path(@article) %> <% end %>
See Checking Abilities for more information
The “authorize!” method in the controller will raise an exception if the user is not able to perform the given action.
def show @article = Article.find(params[:id]) authorize! :read, @article end
Setting this for every action can be tedious, therefore the load_and_authorize_resource
method is provided to automatically authorize all actions in a RESTful style resource controller. It will use a before filter to load the resource into an instance variable and authorize it for each action.
class ArticlesController < ApplicationController load_and_authorize_resource def show # @article is already loaded and authorized end end
See Authorizing Controller Actions for more information.
If the user authorization fails, a CanCan::AccessDenied
exception will be raised. You can catch this and modify its behavior in the ApplicationController
.
class ApplicationController < ActionController::Base rescue_from CanCan::AccessDenied do |exception| flash[:alert] = exception.message redirect_to root_url end end
See Exception Handling for more information.
If you have any issues with CanCan which you cannot find the solution to in the documentation, please add an issue on GitHub or fork the project and send a pull request.
To get the specs running you should call bundle
and then rake
. Specs currently do not work in Ruby 1.9 due to the RR mocking framework. See the spec/README for more information.
CanCan was inspired by declarative_authorization and aegis. Also many thanks to the CanCan contributors. See the CHANGELOG for the full list.