โฑ๏ธ

Before Action & Callbacks

Inserting common logic before/after action execution

Controller Callbacks (commonly called Filters) automatically invoke specific methods before or after action execution.

Types:

  • before_action โ€” Before action execution (most commonly used)

  • after_action โ€” After action execution

  • around_action โ€” Wraps around the action

Key usage patterns:

class PostsController < ApplicationController
  before_action :authenticate_user!              # Auth check
  before_action :set_post, only: [:show, :edit, :update, :destroy]  # Common data loading
  before_action :authorize_post!, only: [:edit, :update, :destroy]  # Authorization check

  private

  def set_post
    @post = Post.find(params[:id])
  end
end

Use only: / except: options to apply to or exclude specific actions. Use skip_before_action to skip inherited callbacks.

Calling redirect_to or render in a before_action halts the chain and prevents the action from executing.

Key Points

1

Register callback with before_action :method_name

2

Specify scope with only:/except: options

3

Registered before_actions execute in order before the action

4

redirect/render in before_action halts chain โ†’ action not executed

5

Skip inherited callbacks with skip_before_action

6

Multiple before_actions execute in registration order

Pros

  • Manage common logic DRY-ly
  • Declarative โ€” intent is clear
  • Hierarchical callback management via inheritance
  • Fine-grained per-action control (only/except)

Cons

  • Hard to track execution order with many callbacks
  • Implicit behavior makes debugging harder
  • Overusing skip_before_action causes confusion
  • Excessive callbacks complicate Controllers

Use Cases

Authentication check (authenticate_user!) Resource loading (set_post, set_user) Authorization check (authorize!) Logging, audit trail (after_action)