Search⌘ K
AI Features

Use CanCanCan to Implement Role-Based Access

Explore how to implement role-based access control in Rails using CanCanCan. Learn to define user permissions with an Ability class, apply authorization checks in controllers and views, and handle unauthorized access gracefully. This lesson helps you manage complex roles effectively without overcomplicating your authorization setup.

CanCanCan API overview

CanCanCan has two main parts to its API: an Ability class that defines what any given user is allowed to do (including unauthenticated users) and methods to use in controllers or views to check the given user’s access. For example, to allow our entire customer service team to list and view a refund (which would be the Rails actions index and show) but only allow senior managers to create them, we might write code like this:

Ruby 3.1.2
class Ability
include CanCan::Ability
def initialize(user)
if user.present?
if user.department == "customer_service"
can [ :index, :show ], Refund
if user.job_title == "senior manager"
can [ :create, :new] , Refund
end
end
end
end
end

This only defines the permissions. We still need to check them. We can use authorize_resource to apply a permissions check to all the standard controller actions:

class RefundsController < ApplicationControler
  authorize_resource
end

The authorize_resource command can determine ...