Ruby on Rails Authorization with CanCan Getting started with CanCan

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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.



Got any Ruby on Rails Question?