Use Callbacks

This guide shows you how to use lifecycle callbacks to run code at specific points during a model's lifecycle.

Available Callbacks

Validation Callbacks

  • before_validation - Before validations run

  • after_validation - After validations complete

Save Callbacks (create and update)

  • before_save - Before any save operation

  • after_save - After any save operation

Create Callbacks (new records only)

  • before_create - Before inserting a new record

  • after_create - After inserting a new record

Update Callbacks (existing records only)

  • before_update - Before updating an existing record

  • after_update - After updating an existing record

Destroy Callbacks

  • before_destroy - Before deleting a record

  • after_destroy - After deleting a record

Basic Usage

Register a callback by calling its macro with a method name:

Callback Order

When saving a new record:

  1. before_validation

  2. Validations run

  3. after_validation

  4. before_save

  5. before_create

  6. INSERT into database

  7. after_create

  8. after_save

When updating an existing record:

  1. before_validation

  2. Validations run

  3. after_validation

  4. before_save

  5. before_update

  6. UPDATE in database

  7. after_update

  8. after_save

When destroying:

  1. before_destroy

  2. DELETE from database

  3. after_destroy

Halting the Chain

Return false from a before_* callback to halt execution:

Common Use Cases

Normalizing Data

Setting Timestamps

Generating Slugs

Sending Notifications

Multiple Callbacks

You can register multiple callbacks for the same event:

Best Practices

  1. Keep callbacks simple - Complex logic belongs in service objects

  2. Always return true unless you intend to halt

  3. Make callback methods private - They're internal to the model

  4. Avoid external API calls in callbacks without error handling

  5. Test callbacks - Ensure they work as expected

Verify It Works

Last updated

Was this helpful?