How to Use Callbacks in Rails: Syntax and Examples
In Rails,
callbacks are methods that run automatically at certain points in an object's lifecycle, like before saving or after creating a record. You use them by defining methods and linking them with callback macros such as before_save or after_create inside your model.Syntax
Rails callbacks are declared inside models using macros that specify when the callback runs. Common callbacks include before_save, after_create, and before_destroy. You provide a method name or a block to run at that lifecycle event.
Example parts:
before_save :method_namerunsmethod_namebefore saving the record.after_create do ... endruns the block after a new record is created.
ruby
class User < ApplicationRecord before_save :normalize_name after_create :send_welcome_email private def normalize_name self.name = name.strip.titleize end def send_welcome_email # code to send email end end
Example
This example shows a User model that cleans the user's name before saving and prints a message after creation.
ruby
class User < ApplicationRecord before_save :normalize_name after_create :print_welcome_message private def normalize_name self.name = name.strip.capitalize end def print_welcome_message puts "Welcome, #{name}! Your account was created." end end # Usage example in Rails console: user = User.new(name: " alice ") user.save # Output: # Welcome, Alice! Your account was created.
Output
Welcome, Alice! Your account was created.
Common Pitfalls
Common mistakes when using callbacks include:
- Modifying attributes in
after_saveorafter_createwhich won't trigger another save automatically. - Using callbacks for complex business logic instead of service objects, making code hard to maintain.
- Forgetting to make callback methods
private, exposing internal logic. - Causing infinite loops by saving a record inside a
before_savecallback.
ruby
class User < ApplicationRecord # Wrong: modifying attribute after save won't persist changes after_save :change_name private def change_name self.name = "Changed" # This change won't be saved automatically end end # Correct approach: class User < ApplicationRecord before_save :change_name private def change_name self.name = "Changed" end end
Quick Reference
| Callback | When It Runs | Description |
|---|---|---|
| before_validation | Before validation runs | Modify data before validation |
| after_validation | After validation runs | Check or log validation results |
| before_save | Before saving (create or update) | Change data before saving |
| around_save | Wraps save action | Run code before and after save |
| after_save | After saving | Perform actions after save |
| before_create | Before creating new record | Set data before insert |
| after_create | After creating new record | Trigger actions after insert |
| before_update | Before updating record | Modify data before update |
| after_update | After updating record | Actions after update |
| before_destroy | Before deleting record | Cleanup before delete |
| after_destroy | After deleting record | Actions after delete |
Key Takeaways
Use Rails callbacks to run code automatically at specific model lifecycle events.
Define callback methods as private and link them with callback macros like before_save or after_create.
Avoid complex logic in callbacks to keep code maintainable and prevent unexpected side effects.
Modify attributes in before_save or before_create callbacks to ensure changes persist.
Be careful to avoid infinite loops by not saving records inside callbacks that trigger saves.