DEV Community

Ivan Iliukhin
Ivan Iliukhin

Posted on

Small tips that will help you to use ActiveRecord callbacks more efficiently

Everything there is related the Rails 6 but also actual for 5 and 4.

  • Do not use callbacks if you can - callbacks are incredibly helpful when you need to add a function that should run before/after/around specific lifecycle events. If they do not depend from the context it is possible the best choice. But if the model is used almost everywhere and there are a lot of create/update/destroy events adding new callbacks can drastically reduce the application performance. So I recommend to add them only if you absolutely confident and aware about consequences.

Despite the upper warning, you are decided to add a callback to your model. There are a few things that I recommend to keep in mind.


  • Use saved_change_to_attribute? in after_save/after_update to except unnecessary calls. - If your callback should be called only after changes in a limited set of attributes, this method can help with it. For example, you have the model User with fields: email, password, first_name and last_name. The goal is to update related certificates only when the first_name or last_name changed.
class User < ApplicationRecord
  after_update :update_certifcates,
             if: Proc.new{ saved_change_to_first_name? || saved_change_to_last_name? }

  private

  def update_certificates
    User::UpdateCertificates.call(self)
  end
end
Enter fullscreen mode Exit fullscreen mode
  • Use more suitable methods whenever possible - instead of using common methods like: *_save, *_commit, *_validate is better to use more specific: *_update or *_create. It will also reduce the count of calls.

  • Use after_commit instead of after_save when you want to complete the action - If something went wrong in the after_commit callback there will be an error but the action will be finished because it is called when changes are already flushed to the database. Other callbacks will rollback changes, sometimes it can be useful.

  • Do not run expensive operations in callbacks - better to move them into ActiveJobs

If you know other problems with callbacks or know how to make live easier with them, please share in comments.


Some useful links

Top comments (0)