skip to content

With Pundit 2.5 in a Rails forum app, how do `include Pundit::Authorization`, a `PostPolicy` and `authorize @post` decide who may edit a post?

level: juniorimportance: must knowfreq 70%

answer

  1. plain Ruby class named after the model
  2. initialize(user, record), predicate per action
  3. query defaults to action_name plus ?
  4. false raises Pundit::NotAuthorizedError
  5. authorize returns the record

basics

~20 s

authorize @post finds PostPolicy from the record's class, builds it with pundit_user (current_user by default) and the post, and calls the predicate named after the action, such as update?. False raises Pundit::NotAuthorizedError; true returns the post.

solid answer

~40 s

`include Pundit::Authorization` in `ApplicationController` adds `authorize`, `policy`, `policy_scope` and friends (`include Pundit` is the deprecated pre-2.2 form). A policy is a plain Ruby class, `PostPolicy`, initialised with `(user, record)` and exposing predicates such as `update?`. In `PostsController#update`, `authorize @post` infers `PostPolicy` from the record, passes `pundit_user` (which returns `current_user`), and calls `"#{action_name}?"`, so `update?`. If it returns falsy, Pundit raises `Pundit::NotAuthorizedError` carrying `query`, `record` and `policy`; otherwise it returns `@post`. A second argument picks another predicate (`authorize @post, :update?` from a `publish` action), and `policy(@post).update?` reuses the same rule in views. The generated `ApplicationPolicy` denies everything, with `edit?` delegating to `update?` and `new?` to `create?`.

code

ruby · 24 lines
ruby
# app/policies/post_policy.rb
class PostPolicy < ApplicationPolicy
  def update?
    return false unless user

    user.admin? || user.moderator? || record.author_id == user.id
  end

  def destroy?
    user.present? && (user.admin? || user.moderator?)
  end
end

# app/controllers/posts_controller.rb
class PostsController < ApplicationController
  def update
    @post = authorize Post.find(params[:id])
    if @post.update(permitted_attributes(@post))
      redirect_to @post
    else
      render :edit, status: :unprocessable_content
    end
  end
end

go deeper

for a junior

Know that a policy is a plain class with a predicate per action, that authorize calls the one matching the action, and that a refusal raises Pundit::NotAuthorizedError.

for a middle

Explain policy lookup from the model name, the action_name query default, pundit_user, memoised policies and the deny-by-default ApplicationPolicy.

for a senior

Show how you keep controller and view rules identical, handle guests in predicates, and map NotAuthorizedError to the right response.

for a principal

Decide how far plain-Ruby policies scale for the product's permission model before a different structure is warranted.

## The pieces Pundit adds **Pundit** is an authorization gem: once a user is signed in, it answers "may this user do this action to this record?". It has no DSL of its own; rules are **policy classes**, plain Ruby objects with one predicate method per action. Setup is two steps: 1. `include Pundit::Authorization` in `ApplicationController`. This mixes in `authorize`, `policy`, `policy_scope`, `permitted_attributes`, `verify_authorized` and the hook `pundit_user`, and exposes `policy` and `policy_scope` to views. The older `include Pundit` still works but prints a deprecation warning; it has been deprecated since Pundit 2.2. 2. Optionally `rails generate pundit:install`, which writes `app/policies/application_policy.rb`, and `rails generate pundit:policy post` for each model. ## What a policy looks like The generated `ApplicationPolicy` is a **deny-by-default** base class: | Method | Generated body | |---|---| | `initialize(user, record)` | stores `user` and `record` | | `index?`, `show?`, `create?`, `update?`, `destroy?` | `false` | | `new?` | `create?` | | `edit?` | `update?` | For a community forum, `PostPolicy < ApplicationPolicy` overrides what should be allowed: an author may update their own post, a moderator may update or delete any post, and an admin may do everything. ## What `authorize @post` does, step by step Inside `PostsController#update`: 1. **Query**: with no second argument, the query is `"#{action_name}?"`, here `"update?"`. 2. **Policy lookup**: Pundit's `PolicyFinder` takes the record's `model_name` (`Post`) and appends `Policy`, giving `PostPolicy`. A model can override this with a `policy_class` method, and the call can force one with `policy_class:`. 3. **User**: the policy is built with `pundit_user`, which by default calls `current_user`. 4. **Decision**: Pundit calls `PostPolicy.new(user, @post).update?`. A falsy result raises `Pundit::NotAuthorizedError`, whose `query`, `record` and `policy` readers say what was refused; the message reads like `not allowed to PostPolicy#update? this Post`. 5. **Return**: on success `authorize` returns the record, so `@post = authorize Post.find(params[:id])` works. Policies are memoised per record for the request, so calling `policy(@post)` in the view after `authorize @post` reuses the same object. ## Variations interviewers ask about - **A different predicate**: `authorize @post, :update?` in a custom `pin` action reuses the update rule. - **A class instead of an instance**: `authorize Post` in `create`, when there is no record yet; the policy receives the class as `record`. - **Headless policies**: `authorize :dashboard, :show?` finds `DashboardPolicy` for a page with no model. - **Views**: `<% if policy(@post).update? %>` hides the edit link with the same rule the controller enforces. ## Policies are plain Ruby, so they compose Pundit's README stresses that it "doesn't do anything you can't do yourself". That has practical consequences: - shared rules go into a module included by several policies, or into `ApplicationPolicy` helpers such as `moderator?`; - `alias_method :pin?, :update?` makes two predicates share one rule; - one policy can defer to another: a reply's `update?` can call `Pundit.policy!(user, record.post).update?` so editing a reply follows the post's lock state; - predicates are ordinary methods, so they can be unit-tested without a controller. The flip side is that Pundit gives no structure beyond "one class per model, one method per action": consistency across policies is a team convention, not something the gem enforces. ## What Pundit does not do - It does not authenticate. `pundit_user` returns whatever `current_user` returns, possibly `nil`, so predicates must handle a guest or a filter must sign the user in first. - It does not decide the HTTP response. `Pundit::NotAuthorizedError` propagates like any exception until the app maps it to a redirect or a 403. - It does not check that you called `authorize` at all; that is the job of the optional `verify_authorized` filter. - It does not pass extra arguments to predicates. Context beyond user and record goes into the object `pundit_user` returns.

  • What does Pundit::NotAuthorizedError carry, and how is it usually turned into a response?
    It exposes `query` (such as `:update?`), `record` and `policy`, and its message names the policy class and query. Apps either `rescue_from Pundit::NotAuthorizedError` in `ApplicationController` to redirect with a flash, or map it to `:forbidden` in `config.action_dispatch.rescue_responses`. The `query` and policy class can key an I18n message per rule.
  • Why does the generated ApplicationPolicy return false from every predicate?
    It makes the system deny by default: a new policy grants nothing until you write the rule, so a forgotten predicate fails closed instead of open. `new?` and `edit?` delegate to `create?` and `update?` so the form action and its submit action cannot drift apart.
  • In a create action there is no record yet; what do you pass to authorize?
    Either a new unsaved instance (`authorize Post.new`) or the class (`authorize Post`). Both find `PostPolicy`; the policy receives the instance or the class as `record`, so `create?` must not call instance methods on it if you pass the class.

  • include Pundit is the current way to add Pundit to a controller
  • authorize returns false when the user is not allowed
  • Pundit passes the controller params to every policy predicate
  • authorize always checks show? unless told otherwise
  • Pundit signs the user in when current_user is nil

Assumes Pundit 2.5; include Pundit::Authorization replaced include Pundit, which has been deprecated since 2.2 and only warns.