skip to content

With CanCanCan 3.6, what SQL does `Loan.accessible_by(current_ability)` build from the Ability's rules, and when does it raise instead?

level: middleimportance: should knowfreq 42%

answer

  1. default action :index, covered by :read
  2. one can rule: a plain where
  3. can rules OR, cannot wraps with NOT ... AND
  4. associations: :subquery strategy by default
  5. block-only rule: CanCan::Error

basics

~20 s

accessible_by turns the hash conditions of the rules matching :index into a WHERE clause: can rules are ORed, later cannot rules add NOT ... AND, and no matching rule gives an always-false condition. A block-only rule cannot become SQL, so it raises CanCan::Error.

solid answer

~40 s

`Loan.accessible_by(current_ability)` asks the ability for the rules relevant to `:index` (the default action, which `:read` covers) and returns an `ActiveRecord::Relation`. A single `can` rule becomes a plain `where`, such as `WHERE loans.patron_id = 7`. With several rules, CanCanCan folds them from oldest to newest: each `can` wraps the SQL so far as `(new) OR (previous)`, each `cannot` as `not (new) AND (previous)`, and an empty rule set yields an always-false condition, so the user sees nothing. Conditions on associations, such as `book: { branch_id: 3 }`, need joins; the default `:subquery` strategy wraps them as `loans.id IN (SELECT ... LEFT OUTER JOIN books ...)`, while `:left_join` uses `left_joins` plus `distinct`. A block-only rule raises `CanCan::Error`, and so does an Active Record scope rule mixed with other conditions.

code

ruby · 7 lines
ruby
# Ability for a librarian at branch 3 (user id 7)
can :read, Loan, patron_id: user.id
can :read, Loan, branch_id: user.branch_id
cannot :read, Loan, archived: true

# Controller
@loans = Loan.accessible_by(current_ability).order(due_on: :asc)

go deeper

for a junior

Know that Model.accessible_by(current_ability) returns only the records the user may read, as a chainable relation.

for a middle

Explain how can rules become OR, cannot rules NOT ... AND, the always-false empty case, and why block rules raise.

for a senior

Choose a join strategy for association conditions, keep listing rules SQL-translatable, and read the generated SQL when results look wrong.

for a principal

Weigh one rule source for checks and listings against rules that need logic SQL cannot express.

## What `accessible_by` is for A permission check on one record (`can? :read, @loan`) is not enough for an index page: the page must load **only** the loans the user may see, in SQL, so pagination and counts are right. CanCanCan's answer is `accessible_by`, a class method added to every Active Record model: - signature: `accessible_by(ability, action = :index, strategy: CanCan.accessible_by_strategy)`; - the default action is `:index`, which the default `:read` alias covers; - it returns an `ActiveRecord::Relation`, so `.order`, `.includes` and pagination chain on. The important property is that it reuses the **same hash conditions** that `can?` evaluates in Ruby. One rule definition serves both the record check and the listing. ## From rules to a WHERE clause The model adapter takes the rules relevant to the action and subject, in definition order, and builds the condition step by step: 1. **No relevant rule**: an always-false comparison such as `TRUE=FALSE` (the exact literal depends on the database adapter), so the result is empty. 2. **Exactly one `can` rule**: its hash is passed straight to `where`, so `can :read, Loan, patron_id: 7` gives `WHERE "loans"."patron_id" = 7`; a `can` with no conditions gives every row. 3. **Several rules**: starting from the always-false condition, each rule, oldest first, wraps what came before: - a `can` produces `(its conditions) OR (previous)`; - a `cannot` produces `not (its conditions) AND (previous)`. So the newest rule ends up outermost, matching the newest-first precedence of `can?`. | Ability rules for a librarian | Resulting condition (simplified) | |---|---| | `can :read, Loan, patron_id: 7` | `loans.patron_id = 7` | | plus `can :read, Loan, branch_id: 3` | `(loans.branch_id = 3) OR (loans.patron_id = 7)` | | plus `cannot :read, Loan, archived: true` | `not (loans.archived = TRUE) AND ((loans.branch_id = 3) OR (loans.patron_id = 7))` | A rules compressor (on by default, `CanCan.rules_compressor_enabled = false` to disable) simplifies the list first: a rule with no conditions, a catch-all, makes the rules before it irrelevant, and rules repeating an earlier condition collapse, which keeps the SQL short. ## Conditions on associations and the query strategy A nested hash such as `can :read, Loan, book: { branch_id: user.branch_id }` refers to another table, so a join is needed. `CanCan.accessible_by_strategy` decides how: | Strategy | SQL shape | Note | |---|---|---| | `:subquery` (default on Active Record 5+) | `WHERE loans.id IN (SELECT loans.id FROM loans LEFT OUTER JOIN books ... WHERE ...)` | no duplicate rows, outer query stays simple | | `:left_join` | `left_joins(:book)` plus `distinct` | the docs warn that `distinct` is not reliable in every case | | `:joined_alias_exists_subquery`, `:joined_alias_each_rule_as_exists_subquery` | `EXISTS` subqueries | added in 3.4 | Set it globally in an initializer, or per call since 3.3: `Loan.accessible_by(current_ability, :index, strategy: :left_join)`. ## When it raises instead - **A block-only rule** for the action raises `CanCan::Error` ("The accessible_by call cannot be used with a block 'can' definition"), because Ruby code cannot become SQL. Give the rule a hash, or an SQL fragment alongside the block. - **An Active Record scope used as a rule's conditions** (`can :read, Loan, Loan.overdue do |loan| ... end`) works alone, but mixed with other rules for the same action it raises "Unable to merge an Active Record scope with other conditions". - `can?` on a rule defined only with raw SQL raises, because that rule cannot be checked in Ruby. ## Using it well - Index actions: `Loan.accessible_by(current_ability).includes(:book).order(due_on: :asc)`. - Other actions: `Loan.accessible_by(current_ability, :update)` lists only loans the user may edit. - Keep listing rules as hashes; reserve blocks for actions that never need a list.

  • load_and_authorize_resource leaves @loans nil on index; what in the Ability causes that?
    A block-only rule for the index action. The controller resource checks `has_block?` before calling `accessible_by`, and skips loading the collection when the rules cannot become SQL, instead of raising. The action then sees a nil `@loans`. Replace the block with hash conditions, or load the collection yourself.
  • Why might the default :subquery strategy be preferred over :left_join?
    A left join against a has-many association multiplies rows, so `:left_join` must add `distinct`, which the CanCanCan docs warn is not reliable in every case, for example with some ORDER BY or select clauses. `:subquery` keeps the outer query on the loans table alone and filters with `id IN (subquery)`, so no duplicates appear.

  • accessible_by loads every row and filters them with can? in Ruby
  • A block rule is translated into SQL automatically
  • With no matching rule accessible_by returns every record
  • accessible_by defaults to the :read action rather than :index
  • The :left_join strategy is the default on current Active Record

Assumes CanCanCan 3.6: the :subquery strategy and the strategy option arrived in the 3.x series (per-query strategy: since 3.3, EXISTS strategies since 3.4, the compressor switch since 3.5).