Why choose us Know us deep, try our developers before you hireILE & CLOUD for 13 strong years!!! Let's Discuss
Know our success stories Have a look at our works, get satisfied and then decide upon us to hire View More
Why choose us Know us deep, try our developers before you hireILE & CLOUD for 13 strong years!!! Let's Discuss
Know our success stories Have a look at our works, get satisfied and then decide upon us to hire View More
How to use ActiveRecord Callbacks in Rails by Jayadev Das T T T T November 12, 2012June 12, 2021 Stay up to date with the latest tips and techniques of web and mobile app development services. Please leave this field empty Thanks for subscribing Andolasoft Blog! 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. 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 Related Posts: Module in Ruby and its Usages in ‘Rails’ The Best practices for Rails App Development Rails 5 – Most Effective Features for Apps Upgradation