Rails Callbacks


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
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s