Participating in the Monitoring Process

Get an overview of how we can monitor the Active Record process and group the related callbacks together.

Active record and the object

Active Record controls the life cycle of model objects. It creates them, monitors them as they are modified, saves and updates them, and watches as they are destroyed. Using callbacks, Active Record lets our code participate in this monitoring process. We can write code that gets invoked at any significant event in the life of an object. With these callbacks, we can perform complex validation, map column values as they pass in and out of the database, and even prevent certain operations from completing.

Active Record defines sixteen callbacks. Fourteen of these form before-after pairs and bracket some operation on an Active Record object. For example, the before_destroy callback will be invoked just before the destroy() method is called, and after_destroy will be invoked after. The two exceptions are after_find and after_initialize, which have no corresponding before_xyz callback. These two callbacks are different in other ways, too, as we’ll see later.

In the following figure, we can see how Rails wraps the sixteen paired callbacks around the basic create, update, and destroy operations on model objects. Perhaps surprisingly, the before and after validation calls are not strictly nested, though.

Get hands-on with 1200+ tech skills courses.