0
0
RailsHow-ToBeginner · 3 min read

How to Use after_action in Rails: Syntax and Examples

In Rails, after_action is a controller callback that runs specified methods after controller actions finish. You use it by declaring after_action :method_name inside your controller to execute code like logging or cleanup after each action.
📐

Syntax

The after_action callback is declared inside a Rails controller. It takes one or more method names as symbols to run after controller actions complete. You can also specify options like only or except to control which actions trigger the callback.

  • after_action :method_name - runs method_name after every action.
  • after_action :method_name, only: [:show, :index] - runs only after show and index actions.
  • after_action :method_name, except: [:new] - runs after all actions except new.
ruby
class ArticlesController < ApplicationController
  after_action :log_action

  def show
    # action code
  end

  private

  def log_action
    Rails.logger.info "Action completed"
  end
end
💻

Example

This example shows a controller using after_action to log a message after the create action only. It demonstrates how to limit the callback to specific actions.

ruby
class UsersController < ApplicationController
  after_action :send_welcome_email, only: [:create]

  def create
    @user = User.new(user_params)
    if @user.save
      render plain: "User created"
    else
      render plain: "Error", status: :unprocessable_entity
    end
  end

  private

  def send_welcome_email
    # Imagine sending email here
    Rails.logger.info "Welcome email sent to #{@user.email}"
  end

  def user_params
    params.require(:user).permit(:email, :password)
  end
end
Output
User created # In logs: Welcome email sent to user@example.com
⚠️

Common Pitfalls

Common mistakes when using after_action include:

  • Trying to modify the response or redirect inside an after_action, which runs too late to affect the response.
  • Not using only or except options, causing callbacks to run on unintended actions.
  • Using after_action for tasks better suited for around_action or before_action.

Always keep after_action for tasks like logging or cleanup that do not change the response.

ruby
class PostsController < ApplicationController
  # Wrong: trying to redirect in after_action (won't work)
  after_action :redirect_somewhere

  def index
    # action code
  end

  private

  def redirect_somewhere
    redirect_to root_path # This will be ignored
  end
end

# Correct approach:
class PostsController < ApplicationController
  before_action :redirect_somewhere, only: [:index]

  def index
    # action code
  end

  private

  def redirect_somewhere
    redirect_to root_path
  end
end
📊

Quick Reference

Use this quick guide to remember after_action usage:

UsageDescription
after_action :method_nameRun method after every action
after_action :method_name, only: [:show, :edit]Run method only after specified actions
after_action :method_name, except: [:destroy]Run method after all except specified actions
Use for logging, cleanup, notificationsDo not modify response or redirect here

Key Takeaways

Use after_action to run code after controller actions finish.
Limit callbacks with only or except options to avoid unintended runs.
Do not try to change the response or redirect inside after_action callbacks.
Ideal for logging, cleanup, or sending notifications after actions.
Use before_action or around_action for response modifications.