...

/

Use CanCanCan to Implement Role-Based Access

Use CanCanCan to Implement Role-Based Access

Learn about CanCanCan and its use in role-based access in our Rails application.

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:

Press + to interact
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
...