Rails ActiveRecord Callbacks

Techie     November 2022

Definition

Callbacks are methods that are called at some points of an object’s lifecycle. They are basically code that will execute before we can respond to a request. Callbacks are always called before particular controller actions (usually listed on top of the file). The reason for this is that you need to find an object from the database and assign it to an instance variable in all those actions.

Callbacks are private because we dont want to access these actions outside the class.

A callback method is meant to keep the code DRY (Do not Repeat Yourself), because if you don’t have a private method for this, you would have to copy/paste the line inside the method for each controller action. Which is fine as long as you don’t need to change it EVER. That is why it is good practice to use callbacks for these kinds of methods.


Example

class ClientsController < ApplicationController

  before_action :set_client, only: [:show, :edit, :update, :destroy]


  def show
  
  end


  def edit

  end


  def update
    respond_to do |format|
      if @client.update(client_params)
        format.html { redirect_to @client, notice: 'Client was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @client.errors, status: :unprocessable_entity }
      end
    end
  end


  def destroy
    @client.destroy
    respond_to do |format|
      format.html { redirect_to clients_url, notice: 'Client was successfully deleted.'  }
      format.json { head :no_content }
    end
  end


  private
    # Use callbacks to share common setup or constraints between actions.
    def set_client
      @client = Client.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def client_params
      params.require(:client).permit(:name, :address, :phone, :email, :is_closed, :notes, :client_category_id, :sales_channel_id)
    end
end


Callback Types

On Object Initialized

  • after_initialize

Before Transaction is Committed

  • before_validation
  • after_validation
  • before_save
  • around_save
  • after_save
  • before_create
  • around_create
  • after_create

On Rollback

  • after_rollback

After Transaction is Committed Successfully

  • after_create_commit
  • after_commit


Order of Operations

Creating an Object

  • before_validation
  • after_validation
  • before_save
  • around_save
  • before_create
  • around_create
  • after_create
  • after_save
  • after_commit/after_rollback

Updating an Object

  • before_validation
  • after_validation
  • before_save
  • around_save
  • before_update
  • around_update
  • after_update
  • after_save
  • after_commit/
    after_rollback

Destroying an Object

  • before_destroy
  • around_destroy
  • after_destroy
  • after_commit/
    after_rollback


Thanks for reading, see you in the next one!