Callbacks are methods that get called at certain moments of an object’s life cycle. With callbacks it’s possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.
For example, a before_destroy callback can be called to destroy associated objects. (This is best done on the association with :dependent => :destroy, but it makes sense here too.)
You can also stop the destroy process if you have dependent objects you can’t destroy by returning false.
I’ve used ActiveRecord Callbacks to:
- Set default values
- Format specific fields (like phone numbers)
- Send emails when an object is updated or deleted
- Create child objects from comma delimited lists in a string
- Change an object’s state