Latest Rails Interview Question

What is callback in rails ?

Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.

What is the difference between after create and after save ?

Ans:

after_create only works once - just after the record is first created.
after_save works every time you save the object - even if you're just updating it many years later
So if you want to do this email operation only just the once (and then never again) then use after_create.
If you want to do it every time the object is saved, then do it in after_save
after_create()
Is called after Base.save on new objects that haven‘t been saved yet (no record exists).
after_save()
Is called after Base.save (regardless of whether it‘s a create or update save)

Comments