How to use ActiveRecord Callbacks in Rails
November 12, 2012
Callbacks 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.
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
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=>self.id , :status => true) end end