skip to content

As a library system's authorization rules grow, when would you keep CanCanCan's single Ability class and when move to Pundit's per-model policies?

level: seniorimportance: should knowfreq 44%

answer

  1. one declarative file vs one class per model
  2. hash rules feed both can? and accessible_by
  3. Pundit: predicates plus Scope#resolve
  4. order-dependent rules vs plain Ruby
  5. split abilities with merge before migrating

basics

~20 s

CanCanCan suits rules that fit hash conditions: one Ability answers record checks and, through accessible_by, listings. Pundit suits rules needing Ruby logic per model, at the cost of writing each predicate and its Scope separately and keeping them consistent.

solid answer

~40 s

CanCanCan centralises declarative rules in one `Ability`: a hash condition such as `branch_id: user.branch_id` answers `can?` in Ruby and `accessible_by` in SQL, and `load_and_authorize_resource` wires controllers by convention. That is strong while roles are few and rules are attribute comparisons. It degrades when the file grows long and order-dependent, when rules need Ruby logic (block rules cannot feed `accessible_by`), and when every request builds an ability holding every rule. Pundit gives each model a plain-Ruby `PostPolicy`-style class with one predicate per action and a `Scope#resolve` for listings; logic is unconstrained and files stay small, but the predicate and the scope are two expressions of one rule that can drift, and every action calls `authorize` explicitly. A middle path: split the Ability per model and `merge` them before migrating.

code

ruby · 13 lines
ruby
# CanCanCan: one hash rule answers both questions
can :read, Loan, branch_id: user.branch_id
# can? :read, @loan                    -> Ruby comparison
# Loan.accessible_by(current_ability)  -> WHERE loans.branch_id = 3

# Pundit: the same rule written twice
class LoanPolicy < ApplicationPolicy
  def show? = record.branch_id == user.branch_id

  class Scope < ApplicationPolicy::Scope
    def resolve = scope.where(branch_id: user.branch_id)
  end
end

go deeper

for a junior

Know the shapes: CanCanCan puts every rule in one Ability class, Pundit gives each model its own policy class.

for a middle

Explain how one CanCanCan hash rule serves can? and accessible_by, while Pundit needs a predicate and a Scope.

for a senior

Argue the choice from the rules you actually have: attribute comparisons, domain logic, order dependence, listing needs and test strategy.

for a principal

Plan the migration path, splitting and merging abilities first, and the cost of running two authorization styles during a transition.

## Two models of the same job Both gems answer "may this user do this to this record?" and "which records may this user see?". They differ in **where the rules live** and **what form they take**. **CanCanCan**: - one `Ability` class, built per request from `initialize(user)`; - rules are declarations: `can :update, Loan, branch_id: user.branch_id`; - `can?` and `authorize!` check one record; `accessible_by` turns the **same hash conditions** into SQL for listings; - `load_and_authorize_resource` loads and authorizes by convention. **Pundit**: - one policy class per model, such as `LoanPolicy`, built with `(user, record)`; - one predicate method per action, plain Ruby: `def renew? = record.patron_id == user.id && record.renewals_count < 2`; - a nested `Scope` with `resolve` for listings, written separately; - every action calls `authorize` explicitly; `verify_authorized` is an optional development aid. ## Side by side | Concern | CanCanCan | Pundit | |---|---|---| | Where a rule lives | in one Ability, grouped by role | in the model's policy, grouped by action | | Rule form | hash conditions, or blocks | any Ruby method | | Record check and listing | one hash rule serves both | predicate and `Scope#resolve` written twice | | Precedence | definition order; later rules override | none; each predicate is self-contained | | Controller wiring | `load_and_authorize_resource` conventions | explicit `authorize` and `policy_scope` calls | | Testing | `Ability.new(user).can?(...)`, `be_able_to` | `LoanPolicy.new(user, loan).renew?`, `permit` | ## Where CanCanCan wins 1. **Attribute-shaped rules**: in a library, most rules are "patron owns the loan", "librarian's branch matches", "book is not withdrawn". Hash conditions express each once and give both checks and listings, so they cannot drift. 2. **Seeing all permissions at once**: a reviewer can read every role's powers in one file, which helps audits and role design. 3. **Less controller code**: one macro per controller instead of a call in every action. ## Where it starts to hurt 1. **Order dependence**: as `cannot` exceptions accumulate, the meaning of a line depends on everything below it; a harmless-looking reorder changes permissions. 2. **Logic that is not a hash**: a block rule (renewal limits, holds queues, opening hours) works for `can?` but breaks `accessible_by`, so the listing needs separate code anyway. 3. **Size and cost**: one file with every model's rules, rebuilt for every request, becomes long to read and to evaluate. CanCanCan's own docs show splitting it into per-model ability classes, selecting one with `current_ability` and combining them with `merge`. ## Where Pundit wins, and what it costs - Each policy is small and ordinary Ruby, so complex rules, helper methods and inheritance (`ApplicationPolicy`) are natural. - Rules sit next to the action they guard, and tests target one class. - The cost is duplication: `show?` and `Scope#resolve` express the same visibility rule in two forms, and nothing makes them agree except tests. Explicit `authorize` calls in each action are more typing and, without `verify_authorized`, easier to forget. ## A decision guide - Few roles, rules mostly attribute comparisons, many index pages: **CanCanCan**, kept in hash form. - Rules full of domain logic, many models, teams owning different models: **Pundit**. - An existing CanCanCan app that is straining: first **split the Ability per model and merge**, keep hash rules for listings, and migrate the logic-heavy models to Pundit-style objects only if splitting is not enough. Running both gems in one app is possible but doubles the concepts a reviewer must hold.

  • What is the most common drift bug in a Pundit app that CanCanCan's model avoids?
    A visibility change applied to `show?` but not to `Scope#resolve`, or the reverse: the index lists records the show page refuses, or hides records a direct link still opens. CanCanCan derives both the check and the listing from one hash condition, so they change together, as long as the rule stays a hash.
  • Why can a long CanCanCan Ability become risky to edit?
    Evaluation is newest-first, so a rule's effect depends on every rule defined after it. Moving a role section, or adding a `can` below a `cannot`, silently re-grants or revokes permissions. Splitting abilities per model and keeping `cannot` rules rare limits how far one edit can reach.

  • Pundit generates listing queries from its predicates automatically
  • CanCanCan block rules work with accessible_by like hash rules
  • With CanCanCan you must write a separate scope for every index
  • Pundit rules depend on the order they are defined in
  • CanCanCan cannot split its rules across several ability classes