Wanted to share my thoughts on ActiveRecord Callbacks. I’d like to know your thoughts if you disagree. Please use the comments.
Only use them when the behavior is must have under all situations, including your tests. For example, we know email addresses are case-insensitive. So no matter what, we may always want to store a lower cased version in the db.
Never use them otherwise. A couple of classic examples that I consider as bad:
user.rb
123456789101112131415161718192021
#Bad: Sends email, probably not required under all situations such as when creating via migrations, tests etc.classUser<ActiveRecord::Baseafter_create:welcomedefwelcomeWelcomeMailer.welcome(self).deliverendend#Bad: Interacts with external componentsclassUser<ActiveRecord::Baseafter_create:setup_orientationdefsetup_orientationOrientationMessageQueue.enque(self)endend
A common problem with the callbacks is, there are some handy methods that skip the callbacks. For example, consider the following:
User.rb
12345678910111213141516171819
#CarefulclassUser<ActiveRecord::Basebefore_save:update_coordinatesdefupdate_coordinatesself.coordinates=Geo.find_coordinates(zip_code)endend#works finesohan=User.find_by_name('Sohan')sohan.zip_code='33333'sohan.save!#doesn't fire the callbackUser.update_all({zip_code:'33333'},{zip_code:'55555'})
If you’re using the callbacks, I’d emphasize again, only use when you are absolutely sure the desired behavior applies under all contexts.