Ruby on Rails/ActiveRecord/Callbacks

Callbacks
Callbacks provide a means of hooking into an ActiveRecord object's lifecycle.

Implementing Callbacks
There are four types of callbacks accepted by the callback macros:


 * Method references (symbol)
 * Callback objects
 * Inline methods (using a proc)
 * Inline eval methods (using a string) - deprecated.

Method references and callback objects are the recommended approaches, inline methods using a proc are sometimes appropriate (such as for creating mix-ins) and inline eval methods are deprecated.

Method Reference
The method reference callbacks work by specifying a protected or private method available in the object, like this:

Callback Objects
The callback objects have methods named after the callback, called with the record as the only parameter such as:

So you specify the object you want messaged on a given callback. When that callback is triggered the object has a method by the name of the callback messaged.

Proc
Example of using a Proc for a callback:

Inline Eval
The callback macros usually accept a symbol for the method they’re supposed to run, but you can also pass a "method string" which will then be evaluated within the binding of the callback. Example:

Notice that single plings (’) are used so the #{id} part isn’t evaluated until the callback is triggered. Also note that these inline callbacks can be stacked just like the regular ones:

before_save
This method is called before an ActiveRecord object is saved.

after_save
Once the active record object saved some method will be fired in that scenario we have to use the after_save callback.

before_create
called before creating a new object of the model

after_create
Called after creating new object and just before saving the records

Partially Documented Callbacks
The following callbacks are partially documented. Their use is discouraged because of performance issues.

after_find
The after_find callback is only executed if there is an explicit implementation in the model class. It will be called for each object returned from a find, and thus can potentially affect performance as noted in the Rails API Documentation.

after_initialize
The after_initialize method is only executed if there is an explicit implementation in the model class. It will be called whenever an ActiveRecord model is initialized. It will be called for each object returned from a find, and thus can potentially affect performance as noted in the Rails API documentation.