Skip to the workspace
Pebellslearn by building
Controllers  ›  Lesson

Controller Callbacks (Filters)

Controller Callbacks (filters) 12 minbefore_action, after_action and around_action run shared code around actions, and a before_action that renders or redirects stops the action from running.

ruby on rails / Controller Callbacks (Filters)

Explore each scene at your own pace.

01 · The rule

The rule

Controller Callbacks (Filters)

Look at a typical books controller and four actions begin with the same line: find the book. Several also need the same check: is someone signed in? Copying these lines is how bugs creep in, when one action forgets the check. Callbacks run shared code for you, before or after the actions you choose.

The rule

before_action prepares or guards; a redirect inside it stops the action.

class BooksController < ApplicationController
  before_action :require_member, except: [:index, :show]
  before_action :set_book, only: [:show, :edit, :update, :destroy]

  def show; end          # @book is already set
  def edit; end

  def update
    if @book.update(book_params)
      redirect_to @book
    else
      render :edit, status: :unprocessable_entity
    end
  end

  private

  def set_book
    @book = Book.find(params[:id])
  end

  def require_member
    redirect_to new_session_path, alert: "Please sign in." unless current_member
  end
end

The pieces:

  • before_action runs before the action. Use it to load records or to guard access.
  • after_action runs after the action has produced its response — rarer, for things like logging.
  • around_action wraps the action and must yield to run it — for timing or transactions.
  • only: and except: choose the actions.
  • skip_before_action turns an inherited callback off, for example a sign-in check defined in ApplicationController that the public home page should skip.

Callbacks run in the order they are declared, and parent-class callbacks run before the child's.

The halting rule: if a before_action renders or redirects, Rails stops there. Later callbacks and the action itself do not run.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.