Model Callbacks
Hooks that auto-execute before/after save/delete
Model Callbacks are methods that automatically execute at lifecycle events of ActiveRecord objects such as creation, update, and deletion.
Key callback order (create):
1. before_validation
2. after_validation
3. before_save
4. before_create
5. after_create
6. after_save
7. after_commit (after transaction commit)
class Post < ApplicationRecord
before_save :normalize_title
after_create :send_notification
before_destroy :check_dependencies
private
def normalize_title
self.title = title.strip.titleize
end
def send_notification
NotificationJob.perform_later(self)
end
end
Caution: Too many callbacks make code flow hard to follow and testing complex. Extract complex business logic into Service Objects.
Key Points
before_validation โ normalize data before validation
after_validation โ additional processing after validation
before_save / before_create / before_update โ pre-save logic
after_save / after_create / after_update โ post-save logic
before_destroy / after_destroy โ pre/post-delete logic
after_commit โ after transaction commits (ideal for external APIs, jobs)
Pros
- ✓ Reduces repetitive code (DRY)
- ✓ Ensures data consistency
- ✓ Auto-responds to lifecycle events
- ✓ Declarative โ easy to understand intent
Cons
- ✗ Excessive callbacks make code hard to trace
- ✗ Callback order dependencies may arise
- ✗ Unintended side effects in tests
- ✗ Service Objects are often more appropriate