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 executionaround_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
Register callback with before_action :method_name
Specify scope with only:/except: options
Registered before_actions execute in order before the action
redirect/render in before_action halts chain โ action not executed
Skip inherited callbacks with skip_before_action
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