DEV Community

loading...

Active Record Callbacks Introduction

mcardona9015
・2 min read

All objects created in a rails application have a life cycle, which consists of three general stages: Create, Update, and Destroy. Callbacks allow you to trigger designated methods before, during, or after each stage of an objects life cycle.

Below I will go over some of the basics of an objects lifecycle, as well as a few callback methods and the order in which they will be called.

Create

Object.create
Enter fullscreen mode Exit fullscreen mode

While this one method may seem to only be creating a new object and saving it to the database, there are actually many steps taking place under the hood to achieve this.

  1. Before the object is created it needs to pass its validations.
  2. After the object is validated it is given the okay to be created.
  3. After creation the item is finally saved to the database

Before, during, and after each of these steps takes places we are able to utilize callback methods to perform actions.

Callback methods for Create

  1. before_validation
  2. after_validation
  3. before_save
  4. before_create
  5. after_create
  6. after_save

In order to demonstrate the order the above callbacks are called in we can define a simple user model with a method that puts out the name of each callback.

class User < ApplicationRecord

    before_validation :bv
    after_validation :av
    before_save :bs
    before_create :bc
    after_create :ac
    after_save :as
    after_commit :a_com

    def bv
        puts "before_validation"
    end
    def av
        puts "after_validation"
    end
    def bs
        puts "before_save"
    end
    def bc
        puts "before_create"
    end
    def ac
        puts "after_create"
    end
    def as
        puts "after_save"
    end
Enter fullscreen mode Exit fullscreen mode

Once we create an instance of the user model we can see in the console the order in which the methods are being called as the item is created and then saved to the database.

Alt Text

Update

Object.update
Enter fullscreen mode Exit fullscreen mode

Callback methods for Update

  1. before_validation
  2. after_validation
  3. before_save
  4. before_update
  5. after_update
  6. after_save

Callback methods for Update behave very similarly to the create callbacks.

  • Note: after_save runs both on create and update, but always after the more specific callbacks after_create and after_update

Destroy

Object.destroy
Enter fullscreen mode Exit fullscreen mode

Callback methods for Destroy

  1. before_destroy
  2. after_destroy

Conclusion

There are many uses for callbacks, which are covered in greater detail at the Ruby on Rails guide.
I encourage anyone creating a Rails project to look into them further and utilize there powerful features!

Discussion (0)