ActiveRecord Hooks for Database Events in Ruby

ActiveRecord hooks add addition capability that developers may find very useful. These hooks run some code when you try to add, delete or update a database.

ActiveRecord has two different ways when it comes to hooks implementation: ActiveRecord::Observer and callbacks

ActiveRecord callbacks implemented as part of ActiveRecord::Base class and include: before_save, after_save among others. Here is an example of running after_create callback in ActiveRecord implementation.

class MyClass < ActiveRecord::Base
 def after_create
  puts %{Record was created}
 end
end

my_class = MyClass.create(:name => ‘Title’) //This line will save an object of MyClass type and will call of after_create method.

ActiveRecord callbacks are good for single action and it is not very suitable for multiple actions. In order to accommodate multiple actions after certain event, you can start using ActiveRecord::Observer. It is available from the rails-observer gem. Observers can watch a single class in your code.

In order to implement Observer, you need to create new method of the class that inherit Observer Class as shown in the example below

class MyClass < ActiveRecord::Base
end

class MyClassObserver < ActiveRecord::Observer
 observe MyClass
 
 def after_create
   puts %{Record was created}
  end
end

my_class = MyClass.create(:name => ‘Title’) //This line will save an object of MyClass type and will call of after_create method

Please note that in order for Observer to fire an event, you need to add the following snippet of the code into application.rb file

config.active_record.observers = :class_observer

Please note: if you name your Observer class after method you try to observer, then you don’t need to include class you want to observer inside the method. We presented both ways in one example above. 

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…