Ruby on Rails Getting started with CanCan


Example

CanCan is a a popular authorization library for Ruby on Rails which restricts user access to specific resources. The latest gem (CanCanCan) is a continuation of the dead project CanCan.

Permissions are defined in the Ability class and can be used from controllers, views, helpers, or any other place in the code.

To add authorization support to an app, add the CanCanCan gem to the Gemfile:

gem 'cancancan'

Then define the ability class:

# app/models/ability.rb
class Ability
  include CanCan::Ability

  def initialize(user)
  end
end

Then check authorization using load_and_authorize_resource to load authorized models into the controller:

class ArticlesController < ApplicationController
  load_and_authorize_resource

  def show
    # @article is already loaded and authorized
  end
end

authorize! to check authorization or raise an exception

def show
  @article = Article.find(params[:id])
  authorize! :read, @article
end

can? to check if an object is authorized against a particular action anywhere in the controllers, views, or helpers

<% if can? :update, @article %>
  <%= link_to "Edit", edit_article_path(@article) %>
<% end %>

Note: This assumes the signed user is provided by the current_user method.