Active Record Callbacks in Rails

Callbacks are a great technique for achieving simplicity and flexibility. Callbacks provide a means of hooking into an ActiveRecord object’s life-cycle. A hook is a technique that lets you trap some Ruby event with ActiveRecord, such as object creation. Callbacks are hooks that allow you to trigger logic before or after an alteration of the object state. Callback functions minimizing the length of codes in controllers.

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:

class Post < ActiveRecord::Base
before_save :process_content

private
def process_content
self.content.strip!
end
end

Callback Objects

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

class BankAccount < ActiveRecord::Base
before_save EncryptionWrapper.new(“credit_card_number”)

after_initialize EncryptionWrapper.new(“credit_card_number”)
end

class EncryptionWrapper
def initialize(attribute)
@attribute = attribute
end

def before_save(record)
record.credit_card_number = encrypt(record.credit_card_number)
end

private
def encrypt(value)
# Secrecy is committed
end

end

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:

class Person
before_save Proc.new { |model| model.do_something }
end

Callback Reference

Here are the list of some callback functions

  • 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

  • before_update
  • after_update
  • before_validation
  • after_validation
  • before_validation_on_create
  • after_validation_on_create
  • before_validation_on_update
  • after_validation_on_update
  • before_destroy
  • after_destroy