Active Record Callbacks are predefined methods in the ActiveRecord that allow you to perform actions in specific points of the object lifecycle. This allows us to avoid repetition in our controllers, keeping our code tidy.

Get it? Rails.

The Object Life Cycle

Very simply, the object life cycle in a normal Rails application is Creation > Update > Destruction. Create, Update, Destroy. Active Record callbacks allow us to perform actions at specific points in the cycle.

2 Ways to Implement

In order for a callback to be implemented, you must “register” them. This just means that near the top of your controller, you type the callback you wish to use, and the method that you want to fire right after.

class CardsController < ApplicationControllerbefore_action :find_by_iddef update   puts @cardend
private
def find_by_id @card = Card.find_by_id(params[:id])endend
before_action :find_by_id, only: [:show, :index, :delete, :update]
class CardsController < ApplicationControllerbefore_action do   @card = Card.find_by_id(params[:id])enddef update    puts @cardendend

Callbacks Available to Use

There are a ton of great predefined callback methods in Active Record. Here is the list. They are very self explanatory as to when they will be called.

Creation

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

Update

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

Destroy

  • before_destroy
  • around_destroy
  • after_destroy
  • after_commit/after_rollback

Software Developer — Game Creator — Let’s work together! Reach out on LinkedIn or Twitter @thedrewprint

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store