How to Use before_action in Ruby on Rails

09/19/2021

Contents

In this article, you will learn how to use before_action in Ruby on Rails.

How to use before_action

before_action is a method provided by Ruby on Rails that allows you to define a method that will be executed before a controller action.

Here’s an example of how to use before_action in a Rails controller:

class MyController < ApplicationController
  before_action :authenticate_user

  def index
    # controller code here
  end

  private

  def authenticate_user
    # authenticate user logic here
  end
end

In this example, we've defined a before_action method that calls the authenticate_user method before any actions in the MyController class are executed. This method will run before the index action, which is defined below it.

You can also specify multiple before_action methods, which will be executed in the order they are listed:

class MyController < ApplicationController
  before_action :authenticate_user
  before_action :load_data

  def index
    # controller code here
  end

  private

  def authenticate_user
    # authenticate user logic here
  end

  def load_data
    # load data logic here
  end
end

In this example, both authenticate_user and load_data methods will be executed before the index action.

You can also specify options for before_action, such as only or except, which allow you to specify which actions the method should apply to:

class MyController < ApplicationController
  before_action :authenticate_user, except: [:index]

  def index
    # controller code here
  end

  def show
    # controller code here
  end

  private

  def authenticate_user
    # authenticate user logic here
  end
end

In this example, the authenticate_user method will be executed before all actions except for index.