0
0
Ruby on Railsframework~5 mins

Before and after filters in Ruby on Rails

Choose your learning style9 modes available
Introduction

Before and after filters let you run code automatically before or after certain actions in your Rails controller. This helps keep your code clean and organized.

You want to check if a user is logged in before showing a page.
You need to load some data before running an action.
You want to log information after an action finishes.
You want to clean up or reset something after an action runs.
Syntax
Ruby on Rails
before_action :method_name, only: [:action1, :action2]
after_action :method_name, except: [:action3]

Use before_action to run code before controller actions.

Use after_action to run code after controller actions.

Examples
This runs authenticate_user before every action in the controller.
Ruby on Rails
before_action :authenticate_user

def authenticate_user
  # check if user is logged in
end
This runs set_post only before the show and edit actions.
Ruby on Rails
before_action :set_post, only: [:show, :edit]

def set_post
  @post = Post.find(params[:id])
end
This runs log_action after all actions except index.
Ruby on Rails
after_action :log_action, except: [:index]

def log_action
  Rails.logger.info "Action completed"
end
Sample Program

This controller loads the article before show and edit actions. After show, it logs that the article was viewed.

Ruby on Rails
class ArticlesController < ApplicationController
  before_action :set_article, only: [:show, :edit]
  after_action :log_view, only: [:show]

  def show
    # show article
  end

  def edit
    # edit article
  end

  private

  def set_article
    @article = Article.find(params[:id])
  end

  def log_view
    Rails.logger.info "Article #{@article.id} was viewed"
  end
end
OutputSuccess
Important Notes

Filters help avoid repeating code in each action.

You can use only and except to control which actions run the filters.

Filters run in the order they are defined.

Summary

Before filters run code before controller actions.

After filters run code after controller actions.

Use filters to keep your controller code clean and DRY.