Ruby on Rails : Callbacks V/S Observers

Observers 🧐

Observer lives longer.
It can be attached & detached at any time.
It is used when method is not directly associated to life cycle of Active Record objects.
If you want to create observer with command-line you need to add gem first because without observer gem you couldn’t run any observer generator command so first add this gem “rails-observers”
After that run this command in your terminal :- rails g observer User

Then, bundle install

That above observer command will create new file with name user_observer.rb, Then in this file define the models you wish to observe (One observer use for several classes) and then add the after_create callback


Callback ☎️

Call back is short live compare to observer.
You pass it into a function to be called once, usually user can only pass a single callback
Callbacks are methods which can be called at certain moments of an active record life cycle for example it can be called when an object is created, updated, deleted.
Callbacks allow you to trigger logic before or after an alteration of an object’s state.

Syntax of call back:
after_create :send_invite_link


I hope this will be quite helpful to you guy’s 😊

Thank you 🙏