skip to content

In a CanCanCan Ability, how do the order of can and cannot rules, hash conditions and blocks combine to decide a check on one record?

level: middleimportance: must knowfreq 52%

answer

  1. later rules override earlier ones
  2. can rules are ORed together
  3. cannot belongs after the broader can
  4. block runs only for an instance
  5. hash and block together: BlockAndConditionsError

basics

~20 s

CanCanCan checks the matching rules newest first, so a later rule overrides an earlier one. Multiple can rules are alternatives, a cannot must come after the can it narrows, and a rule takes either a hash of conditions or a block, never both.

solid answer

~40 s

For `can?(:destroy, @loan)` CanCanCan collects the rules whose action and subject match, reverses them so the most recently defined comes first, and returns the verdict of the first one whose conditions match: `true` for a `can`, `false` for a `cannot`, `false` if none matches. Two `can` rules are therefore ORed, and `can :manage, Loan` followed by `cannot :destroy, Loan` forbids deletion, while the reverse order lets `:manage` win. Conditions come in two forms: a hash compared against the record's attributes (and usable by `accessible_by`), or a block that receives the record and returns a boolean. Passing both to one rule raises `CanCan::BlockAndConditionsError`. Blocks run only for instances; for a class subject a conditional `can` matches and a conditional `cannot` is skipped.

code

ruby · 17 lines
ruby
class Ability
  include CanCan::Ability

  def initialize(user)
    return unless user

    can :read, Loan, patron_id: user.id
    can :renew, Loan do |loan|
      loan.patron_id == user.id && loan.renewals_count < 2
    end

    return unless user.librarian?

    can :manage, Loan, branch_id: user.branch_id
    cannot :destroy, Loan, returned_at: nil   # must follow the :manage rule
  end
end

go deeper

for a junior

Remember that later rules override earlier ones, so put cannot after the can it restricts.

for a middle

Explain the reverse-order evaluation, ORed can rules, hash versus block conditions and BlockAndConditionsError.

for a senior

Order role sections deliberately, keep cannot rules rare, and use attribute-level rules and permissions for debugging.

for a principal

Decide when an order-dependent rule file has become too risky to change without a different structure.

## How a single check is decided When code asks `can?(:destroy, @loan)`, CanCanCan's `Ability`: 1. finds the **relevant rules**: those whose actions (after expanding aliases and `:manage`) include `:destroy` and whose subject matches `Loan` (or `:all`); 2. **reverses** them, so the most recently defined rule is examined first; 3. walks that list and stops at the first rule whose **conditions match** the record; 4. returns that rule's **base behaviour**: `true` for a `can`, `false` for a `cannot`; 5. returns `false` if no rule matched. CanCanCan is deny by default. Everything about precedence follows from steps 2 and 3. ## Consequences of "newest first" | Ability body | `can? :destroy, @loan` | Why | |---|---|---| | `can :manage, Loan` then `cannot :destroy, Loan` | `false` | the later `cannot` is checked first and matches | | `cannot :destroy, Loan` then `can :manage, Loan` | `true` | the later `can :manage` is checked first | | `can :read, Loan, patron_id: 7` then `can :read, Loan, branch_id: 3` | either condition grants | `can` rules do not cancel each other: they are alternatives | That is why CanCanCan's documentation puts the general `can` first and the exception after it, and why role blocks are ordered from least to most privileged: in a library, the librarian section adds `cannot :destroy, Loan, returned_at: nil`, and an administrator section further down can re-grant `can :destroy, Loan` because it comes later. ## Hash conditions A hash compares the record's attributes: - `can :update, Loan, branch_id: user.branch_id` matches when `loan.branch_id` equals it; - arrays and ranges match membership: `status: [:active, :overdue]`; - nested hashes follow associations: `can :read, Loan, book: { branch_id: user.branch_id }`. Hash conditions have a second life: `accessible_by` turns them into SQL, and `load_and_authorize_resource` uses scalar values from them as initial attributes when building a new record. ## Block conditions When a rule cannot be written as a hash, a block receives the record: - `can :renew, Loan do |loan| loan.patron_id == user.id && loan.renewals_count < 2 end`; - the block runs only when an **instance** is checked; for a class subject a `can` block rule counts as a match and a `cannot` block rule is skipped; - a block cannot be translated into SQL, so `accessible_by` raises for a block-only rule. A rule takes **either** a hash or a block. `can :renew, Loan, patron_id: user.id do |loan| ... end` raises `CanCan::BlockAndConditionsError` ("A hash of conditions is mutually exclusive with a block"). Put the whole condition in the block, or split it into separate rules. ## Attribute-level rules Since CanCanCan 3.0 a rule can name attributes: `can :update, Loan, :due_on` lets a user update only that field, and `can? :update, @loan, :due_on` checks it. `cannot` with attributes removes fields from an otherwise broad grant. ## Ordering roles in a library A practical layout for `initialize(user)` follows privilege upwards: 1. rules for everyone, including guests (`can :read, Book`); 2. `return unless user`, then patron rules (own loans, holds); 3. librarian rules, each broad grant followed by its exceptions; 4. administrator rules last, so they can re-grant anything a `cannot` above removed. Because each section only adds to or overrides what came before, reading the file top to bottom matches how the roles stack. ## Debugging precedence - `Ability#permissions` returns a hash of every `can` and `cannot` by action and subject, handy in a console. - Read the ability bottom-up for a given action: the first matching rule from the bottom is the answer. - Keep `cannot` rules few; many overrides make the file order-dependent in ways reviewers miss.

  • Why does ability.can?(:destroy, Loan) return true in that example despite the cannot :destroy rule?
    With a class there is no record to compare, so CanCanCan treats a conditional rule as matching only if it is a `can`; a conditional `cannot` is passed over. The newest relevant rule, `cannot :destroy, Loan, returned_at: nil`, is skipped and `can :manage, Loan, branch_id: ...` answers `true`. The instance check `can?(:destroy, loan)` applies the cannot. An unconditional `cannot :destroy, Loan` would make the class check `false`.
  • How do you combine an ownership condition with a rule that needs Ruby logic?
    A single rule cannot take both a hash and a block. Either express everything in the block (`loan.patron_id == user.id && ...`), which loses `accessible_by` for that action, or keep the hash part in its own rule for listings and check the extra logic in the controller or the model.

  • The first rule defined in initialize always wins
  • A cannot rule placed before can :manage still forbids the action
  • Two can rules on the same action must both match
  • A rule can take a hash of conditions and a block together
  • A block rule is evaluated even when a class is checked