How to use ActiveRecord Callbacks in Rails

Rails3
Social sharing

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

before_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

after_save:
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=>self.id , :status => true) end end

Your recently viewed posts:

Jayadev Das - Post Author

Do what you do best in – that’s what I’ve always believed in and that’s what I preach. Over the past 25+ years (yup that’s my expertise ‘n’ experience in the Information Technology domain), I’ve been consulting to small, medium and large companies ‘About Web Technologies, Mobile Future as well as on the good-and-bad of tech. Blogger, International Business Advisor, Web Technology Expert, Sales Guru, Startup Mentor, Insurance Sales Portal Expert & a Tennis Player. And top of all – a complete family man!

[contact-form-7 404 "Not Found"]
Enter your email address to stay up to date with the latest news.
Holler Box

Orange Exit pop up

Subscribe for the latest
trends in web and
mobile app development
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