Active Record Callbacks

Callback Sequence

create update destroy
before_validation before_validation_on_create after_validation after_validation_on_create before_save before_create before_validation before_validation_on_update after_validation after_validation_on_update before_save before_update before_destroy
create operation update operation destroy operation
after_create after_save after_update after_save after_destroy

Three Common Ways to Define Callbacks


# 1. Defining a method
def before_save
  # encrypt password here
end

# 2. Referring to a method with a symbol
before_save :encrypt_password

# 3. With a Proc object
before_save Proc.new { |object| ... }

before_save Example


class User < ActiveRecord::Base
  before_save :encrypt_password

  private
  def encrypt_password
    return if password.blank?
    if new_record?
      self.salt = Digest::SHA1.hexdigest("--#{Time.now.to_s}--#{login}--")
    end
    self.crypted_password = encrypt(password)
  end
end

after_save Example


class Comment < ActiveRecord::Base
  belongs_to :user

  def after_save
    user.update_search_index
  end

  def after_destroy
    user.update_search_index
  end
end

Observers


class AuditObserver < ActiveRecord::Observer 
  observe Order, Payment, Refund 

  def after_save(model) 
    model.logger.info("Audit: #{model.class.name} #{model.id} created") 
  end 
end 

# List your observers in config/environment.rb
config.active_record.observers = :order_observer, :audit_observer

after_find and after_initialize: Must be Methods


def after_find
  # After any find invocation
end

def after_initialize
  # After any object is created
end