skip to content

In CanCanCan, how does one Ability class let library patrons read the catalogue while librarians manage loans, and how is it checked?

level: juniorimportance: must knowfreq 60%

answer

  1. include CanCan::Ability, initialize(user)
  2. can action, subject, conditions
  3. :manage any action, :all any subject
  4. read aliases index and show
  5. authorize! raises CanCan::AccessDenied

basics

~20 s

Every rule lives in Ability#initialize(user) as can or cannot calls: can :read, Book for everyone, can :manage, Loan for librarians. Controllers and views check with can?, and authorize! raises CanCan::AccessDenied when the rule set refuses.

solid answer

~40 s

CanCanCan keeps all permissions in one class, `Ability`, that includes `CanCan::Ability` and builds rules in `initialize(user)` (`rails g cancan:ability` writes it to app/models/ability.rb). `can :read, Book` grants an action on a subject; a third argument adds hash conditions such as `can :read, Loan, patron_id: user.id`; `cannot` removes a permission. `:manage` matches any action and `:all` any subject, and the default aliases map `:read` to `index` and `show`, `:create` to `new`, `:update` to `edit`. Controllers get `current_ability`, memoised as `Ability.new(current_user)`, plus `can?`/`cannot?` (also in views) and `authorize!(action, subject)`, which returns the subject or raises `CanCan::AccessDenied` carrying `action` and `subject`. Guests arrive as `nil`, so `initialize` must handle a missing user.

code

ruby · 26 lines
ruby
# app/models/ability.rb
class Ability
  include CanCan::Ability

  def initialize(user)
    can :read, Book
    return unless user

    can :read, Loan, patron_id: user.id
    return unless user.librarian? || user.admin?

    can :manage, Loan, branch_id: user.branch_id
    cannot :destroy, Loan, returned_at: nil
    can :manage, :all if user.admin?
  end
end

# app/controllers/loans_controller.rb
class LoansController < ApplicationController
  def renew
    @loan = Loan.find(params[:id])
    authorize! :update, @loan   # raises CanCan::AccessDenied when refused
    @loan.renew!
    redirect_to @loan, status: :see_other
  end
end

go deeper

for a junior

Know that rules live in Ability#initialize as can and cannot calls, and that authorize! raises CanCan::AccessDenied while can? returns a boolean.

for a middle

Explain :manage and :all, the read, create and update aliases, current_ability, and why class checks ignore conditions.

for a senior

Handle guests and custom actions safely, choose narrow action lists over :manage, and test abilities directly.

for a principal

Judge when one central rule file stays reviewable for the organisation and when to split it.

## One class holds every rule **CanCanCan** is an authorization gem built around a single idea: every permission in the application is declared in one place, an **Ability** class. `rails generate cancan:ability` writes `app/models/ability.rb`: - it includes `CanCan::Ability`; - its `initialize(user)` receives the signed-in user (or `nil` for a guest); - inside, `can` and `cannot` calls declare rules. CanCanCan mixes `CanCan::ControllerAdditions` into every Action Controller class automatically, so controllers get `current_ability`, `can?`, `cannot?`, `authorize!` and the `load_and_authorize_resource` family without an include. ## Declaring rules for a library In a library system, patrons browse the catalogue and see their own loans; librarians handle loans at their branch; administrators can do anything: | Rule | Meaning | |---|---| | `can :read, Book` | anyone may list and view books | | `can :read, Loan, patron_id: user.id` | a patron sees only their own loans | | `can :manage, Loan, branch_id: user.branch_id` | a librarian may do anything with their branch's loans | | `cannot :destroy, Loan, returned_at: nil` | nobody deletes a loan that is still out | | `can :manage, :all` | administrators may do everything | The vocabulary: 1. **Action**: a symbol such as `:read`, `:create`, `:update`, `:destroy`, or any custom one such as `:renew`. `:manage` is a wildcard that matches **every** action, custom ones included. 2. **Subject**: usually a model class; `:all` matches any subject, and a plain symbol (`:reports`) works for screens with no model. 3. **Conditions**: an optional hash the record must match, or a block that receives the record. CanCanCan ships three default **aliases**: `read: [:index, :show]`, `create: [:new]`, `update: [:edit]`. So `can :read, Book` answers `can? :index, Book` and `can? :show, @book`. `alias_action :renew, :extend, to: :prolong` adds your own. ## Checking rules - **`can?(action, subject)`** returns a boolean. In a view, `<% if can? :update, @loan %>` hides a button. - **`cannot?`** is its negation. - **`authorize!(action, subject)`** returns the subject when allowed and otherwise raises **`CanCan::AccessDenied`**, whose readers `action`, `subject` and `conditions` describe the refusal and whose default message is "You are not authorized to access this page.", overridable through the `unauthorized` I18n keys. - **`current_ability`** is `@current_ability ||= ::Ability.new(current_user)`. Override it when the user comes from somewhere else, for example `Current.user`, or when a controller should use a smaller ability class. ## Two behaviours that surprise newcomers - **Class checks skip conditions.** `can? :update, Loan` is `true` for a librarian with `can :manage, Loan, branch_id: 3`, because a class has no `branch_id` to compare: a conditional `can` rule counts as a match, and a conditional `cannot` rule is passed over. The question it answers is "may this user update **some** loan?". Check the instance once it is loaded. - **Guests must be handled.** With no signed-in user, `initialize(nil)` runs; calling `user.librarian?` raises `NoMethodError`. The generated template's commented example begins with `return unless user.present?`; rules meant for guests must come before such a guard. ## Where the user and the ability come from `current_ability` calls `current_user`, which Devise defines. An app on Rails 8's authentication generator has no `current_user`, so it overrides `current_ability` to build `Ability.new(Current.user)`. The same override lets a controller use a smaller ability class, which CanCanCan's docs suggest once the single file grows. Abilities are built once per request and memoised, so rules can read the user's role and branch freely, but they should not run queries per rule: every request that checks a permission pays for building the whole ability. ## Testing an ability Because the class is plain Ruby, tests build it directly: `ability = Ability.new(patron)` then `assert ability.can?(:read, loans(:mine))` and `assert ability.cannot?(:read, loans(:someone_elses))`. RSpec users get a `be_able_to(:read, loan)` matcher from `cancan/matchers`.

  • Why does can? :update, Loan return true for a librarian whose rule is limited to their branch?
    Conditions are ignored when the subject is a class: there is no record whose `branch_id` could be compared, so CanCanCan answers whether the user may update some loan. This is deliberate, because `authorize_resource` has only the class to check on index. Check the instance, `can? :update, @loan`, once it exists.
  • What does :manage cover that a list of the four CRUD aliases does not?
    Every action, including custom ones such as `:renew` or `:export`, and future actions nobody has written yet. `can :manage, Loan` therefore grants more than `can [:read, :create, :update, :destroy], Loan`, which is why a narrower list is safer for roles below administrator.

  • can :manage, Loan grants only the seven RESTful actions
  • authorize! returns false when the user lacks permission
  • can? :update, Loan evaluates the hash conditions against every loan
  • CanCanCan needs an include in each controller before authorize! works
  • can :read, Book does not cover the index action