skip to content

With Pundit, how does `policy_scope(Post)` decide which forum posts an index lists, and why use it in show as well?

level: middleimportance: must knowfreq 60%

answer

  1. PostPolicy::Scope nested class
  2. initialize(user, scope), then resolve
  3. returns a relation, not a boolean
  4. generated resolve raises NoMethodError
  5. find through the scope: 404, not 403

basics

~10 s

policy_scope(Post) builds PostPolicy::Scope with pundit_user and Post and returns its resolve, usually a filtered relation. Finding the show record through that relation keeps hidden posts unreachable and turns them into a not-found error.

solid answer

~30 s

A Pundit scope is a class named `Scope` nested in the policy, initialised with `(user, scope)` and answering `resolve`. `policy_scope(Post)` instantiates `PostPolicy::Scope.new(pundit_user, Post)` and returns `resolve`, typically an `ActiveRecord::Relation` such as `scope.where(removed_at: nil)` for members and `scope.all` for moderators. The generated `ApplicationPolicy::Scope#resolve` raises `NoMethodError` until you define it, and a missing scope class raises `Pundit::NotDefinedError`. Using `policy_scope(Post).find(params[:id])` in `show` reuses the same visibility rule, so a removed post raises `ActiveRecord::RecordNotFound` (a 404) instead of revealing it exists. Calling `policy_scope` in a controller also marks the action as scoped for `verify_policy_scoped`; the view helper of the same name does not.

code

ruby · 21 lines
ruby
class PostPolicy < ApplicationPolicy
  class Scope < ApplicationPolicy::Scope
    def resolve
      return scope.where(removed_at: nil) unless user
      return scope.all if user.admin? || user.moderator?

      scope.where(removed_at: nil).or(scope.where(author_id: user.id))
    end
  end
end

class PostsController < ApplicationController
  def index
    @posts = policy_scope(Post).order(created_at: :desc)
  end

  def show
    @post = policy_scope(Post).find(params[:id])  # RecordNotFound when hidden
    authorize @post
  end
end

go deeper

for a junior

Know that policy_scope(Post) returns only the records the user may see, defined in the policy's nested Scope#resolve.

for a middle

Explain Scope's constructor and resolve, the NoMethodError and NotDefinedError failure modes, memoisation, and the view helper's difference.

for a senior

Argue for loading show records through the scope, keep resolve as SQL for pagination, and handle nil users explicitly.

for a principal

Weigh one visibility rule shared by listing and lookup against separate predicates as the permission model grows.

## Predicates answer yes or no; scopes answer "which ones" A Pundit predicate such as `show?` decides about **one record**. An index page needs a **collection**: every post the current user may see. Checking `show?` on each row after loading them all is slow and breaks pagination, so Pundit has a second kind of object, the **policy scope**. By convention it is a class called `Scope` nested inside the policy: - it is initialised with `(user, scope)`, where `scope` is usually a model class or an `ActiveRecord::Relation`; - it implements `resolve`, which returns something iterable, normally a relation with the visibility rule applied as SQL; - it inherits from `ApplicationPolicy::Scope`, which stores `user` and `scope` as private readers. ## Writing the forum rule In a community forum, members see posts that have not been removed plus their own removed ones, and moderators see everything. `resolve` expresses that as a query, so the database does the filtering: | User | `resolve` returns | |---|---| | guest (`nil`) | `scope.where(removed_at: nil)` | | member | live posts `or` posts they wrote | | moderator or admin | `scope.all` | Because `pundit_user` can be `nil`, `resolve` must handle guests explicitly or the closed-system pattern must raise in `initialize`. ## What `policy_scope` does `policy_scope(Post)` in a controller: 1. sets an internal flag so `verify_policy_scoped` will pass; 2. looks up the scope class through `PolicyFinder`: `Post` gives `PostPolicy::Scope`; 3. builds it with `pundit_user` and `Post` and calls `resolve`; 4. memoises the result per scope argument for the rest of the request. Failure modes come straight from the source: - no `PostPolicy::Scope` class: `Pundit::NotDefinedError` ("unable to find scope"); - the generated policy's `Scope` with `resolve` still commented out: `NoMethodError` "You must define #resolve in PostPolicy::Scope", deliberate: Pundit has required an explicit `resolve` since 2.2 (the `NoMethodError` form since 2.3.2), so nobody ships an accidental `scope.all`; - `policy_scope(Post, policy_scope_class: ArchivedPostPolicy::Scope)` forces another scope class. ## Why `show` should find through the scope too Two styles exist for `show`: 1. `@post = Post.find(params[:id]); authorize @post` runs the `show?` predicate. 2. `@post = policy_scope(Post).find(params[:id])` uses the scope. The second keeps **one rule** for "what may this user see" instead of a predicate and a scope that can drift apart. It also changes the failure: a hidden post raises `ActiveRecord::RecordNotFound`, which Rails answers with 404, so the response does not confirm the post exists. Many teams do both, scope for loading and `authorize` for the action check, which also satisfies `verify_authorized`. ## Scopes in views and elsewhere - Views can call `policy_scope(@topic.posts)`. The view helper goes through `Pundit::Helper`, which resolves the scope but does **not** set the controller's "scoped" flag, so it never satisfies `verify_policy_scoped`. - Outside a controller (a job, a mailer, the console), `Pundit.policy_scope!(user, Post)` builds the same scope with an explicit user. - A scope can start from an association: `policy_scope(@topic.posts)` narrows a relation that is already narrowed. ## Scopes, pagination and performance Because `resolve` returns a relation, everything after it still composes in SQL: - `policy_scope(Post).includes(:author).order(created_at: :desc)` adds eager loading and ordering; - a pagination gem's call wraps the scoped relation, so page counts reflect only visible posts; - `policy_scope(Post).where(topic: @topic)` narrows further without a second rule. Keep `resolve` free of per-row Ruby logic. A condition that cannot be written as SQL (for example a call to an external service per post) does not belong in a scope; model it as a column or a join the query can use, or check it per record with a predicate after loading a page. ## Common mistakes - Returning an `Array` from `resolve` (for example `scope.select { ... }`), which loads every row and loses chaining and pagination. - Writing `scope.all` as a placeholder and forgetting it. - Assuming `policy_scope` authorizes the action; it only filters what is loaded.

  • Why does the generated Scope#resolve raise instead of returning scope.all as a placeholder?
    A placeholder `scope.all` silently shows every record to every user if someone forgets to replace it. Raising `NoMethodError` with "You must define #resolve" fails loudly the first time the scope is used, matching the deny-by-default predicates in the generated `ApplicationPolicy`; Pundit has required an explicit `resolve` since 2.2.
  • Does calling policy_scope in a view satisfy verify_policy_scoped?
    No. Views reach `policy_scope` through `Pundit::Helper`, which calls the private `pundit_policy_scope` and resolves the scope without setting the controller's scoped flag. Only the controller's `policy_scope` (or `skip_policy_scope`) marks the action, so an index that scopes only in its view still raises `Pundit::PolicyScopingNotPerformedError`.

  • policy_scope returns true or false like a predicate
  • resolve should load the records and filter them in Ruby
  • A missing Scope class makes policy_scope return every record
  • Calling policy_scope in the view satisfies verify_policy_scoped
  • policy_scope also authorizes the current action