How to use ActiveRecord Callbacks in Rails

Rails3 50x50

Rails3Callbacks are a great technique for achieving simplicity and flexibility. A callback allows you to run some code (usually a method) automatically when another piece of code runs. In Rails, you’ll commonly see callbacks that run before, after or even around other bits of code. Callback functions are 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

Here is the list of some useful callback functions while saving AcriveRecord objects

  • before_save
  • after_save


This method is called before an ActiveRecord object is saved.

class Post < ActiveRecord::Base before_save :update_slug protected def update_slug self[:slug] = [year, season_slug, season_type_slug].compact.join '/' end end

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

class Post < ActiveRecord::Base after_save :handle_status_changed protected def handle_status_changed Setting.create(:post_id=> , :status => true) end end

Your recently viewed posts:

    Contact Us

    We’d love to help & work with you

    When do you want to start ?

    Enter your email address to stay up to date with the latest news.
    Holler Box

    Exit pop up

    Sad to see you leaving early...

    From "Aha" to "Oh shit" we are sharing everything on our journey.
    Enter your email address to stay up to date with the latest news.
    Holler Box