Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 28, 2021 08:06 pm GMT

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)  endend
  • 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


Original Link: https://dev.to/evanilukhin/small-tips-that-will-help-you-to-use-activerecord-callbacks-more-efficiently-4i91

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To