Ruby on Rails object lifecycle and callbacks

Callbacks

In ROR, the lifecycle of an object is attached to the database of the application. Objects are created in memory first then later stored in the database.

An object have following lifecycle

  1. Creation
  2. Validation
  3. Save
  4. Update
  5. Deletion

These lifecycle have callbacks attached to each of them by which we can inject our custom logic.

Creation callbacks

  • before_create
  • after_create
  • around_create
  • before_save
  • after_save
  • around_save

Validation callbacks

  • before_validation
  • after_validation

Validation callbacks get execute whenever a new object is saved or it gets updated

Save callbacks

  • before_save
  • after_save
  • around_save

Save callbacks will called for both Model.create and Model.save methods

Update callbacks

  • before_update
  • after_update
  • around_update

Delete object callbacks

  • before_destory
  • after_destroy
  • around_destroy

Sequence in which callbacks gets called.

For Creating an object.

Following sequence of callbacks get called when Model.create is invoked.

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

For Updating an object

Following sequence of callbacks get called when Model.update is invoked.

  • before_validation
  • after_validation
  • before_save
  • around_save
  • before_commit
  • before_update
  • around_update
  • after_update
  • after_save
  • after_commit

For deleting an object

Following sequence of callbacks get called when Model.destroy is invoked.

  • before_destroy
  • around_destroy
  • after_destroy
  • after_commit

Read Also: Demystifying ActiveRecord query generation – Arel

Observations:

  1. after_commit is always called in the end
  2. before_commit gets called before_update, before_save and before_create
  3. before_validation and after_validation will executed before any other callbacks
  4. around_* callbacks are called after before_* callbacks
  5. General sequence, before_save, around_save, before_commit, before_create/update, around_create/update
  6. After sequence follows, after_create/update, after_save, after_commit

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *