Home > Articles > Web Development

This chapter is from the book

This chapter is from the book

9.2 Callbacks

This advanced feature of Active Record allows the savvy developer to attach behavior at a variety of different points along a model’s life cycle, such as after initialization; before database records are inserted, updated, or removed; and so on.

Callbacks can do a variety of tasks, ranging from simple things such as the logging and massaging of attribute values prior to validation to complex calculations. Callbacks can halt the execution of the life cycle process taking place. Some callbacks can even modify the behavior of the model class on the fly. We’ll cover all those scenarios in this section, but first let’s get a taste of what a callback looks like. Check out the following silly example:


1 class Beethoven < ActiveRecord::Base
2   before_destroy :last_words
3
4   protected
5
6   def last_words
7     logger.info "Friends applaud, the comedy is over"
8   end
9 end

So prior to dying (ehrm, being destroyed), the last words of the Beethoven class will always be logged for posterity. As we’ll see soon, there are 14 different opportunities to add behavior to your model in this fashion. Before we get to that list, let’s cover the mechanics of registering a callback.

9.2.1 One-Liners

Now if (and only if) your callback routine is really short,2 you can add it by passing a block to the callback macro. We’re talking one-liners!


class Napoleon < ActiveRecord::Base
  before_destroy { logger.info "Josephine..." }
  ...
end

Since Rails 3, the block passed to a callback is executed via instance_eval so that its scope is the record itself (versus needing to act on a passed-in record variable). The following example implements “paranoid” model behavior, covered later in the chapter.


1 class Account < ActiveRecord::Base
2   before_destroy { self.update_attribute(:deleted_at, Time.now); false }
3   ...

9.2.2 Protected or Private

Except when you’re using a block, the access level for callback methods should always be protected or private. It should never be public, since callbacks should never be called from code outside the model.

Believe it or not, there are even more ways to implement callbacks, but we’ll cover those techniques later in the chapter. For now, let’s look at the lists of callback hooks available.

9.2.3 Matched before/after Callbacks

In total, there are 19 types of callbacks you can register on your models! Thirteen of them are matching before/after callback pairs, such as before_validation and after_validation. Four of them are around callbacks, such as around_save. (The other two, after_initialize and after_find, are special, and we’ll discuss them later in this section.)

9.2.3.1 List of Callbacks

This is the list of callback hooks available during a save operation. (The list varies slightly depending on whether you’re saving a new or existing record.)

  • before_validation
  • after_validation
  • before_save
  • around_save
  • before_create (for new records) and before_update (for existing records)
  • around_create (for new records) and around_update (for existing records)
  • after_create (for new records) and after_update (for existing records)
  • after_save

Delete operations have their own callbacks:

  • before_destroy
  • around_destroy, which executes a DELETE database statement on yield
  • after_destroy, which is called after record has been removed from the database and all attributes have been frozen (readonly)

Callbacks may be limited to specific Active Record life cycles (:create, :update, :destroy) by explicitly defining which ones can trigger it using the :on option. The :on option may accept a single lifecycle (like on: :create) or an array of life cycles (like on: [:create, :update]).

# Run only on create.
before_validation :some_callback, on: :create

Additionally, transactions have callbacks as well for when you want actions to occur after the database is guaranteed to be in a permanent state. Note that only “after” callbacks exist here due to the nature of transactions—it’s a bad idea to be able to interfere with the actual operation itself.

  • after_commit
  • after_rollback
  • after_touch

9.2.4 Halting Execution

If you return a boolean false (not nil) from a callback method, Active Record halts the execution chain. No further callbacks are executed. The save method will return false, and save! will raise a RecordNotSaved error.

Keep in mind that since the last expression of a Ruby method is returned implicitly, it is a pretty common bug to write a callback that halts execution unintentionally. If you have an object with callbacks that mysteriously fails to save, make sure you aren’t returning false by mistake.

9.2.5 Callback Usages

Of course, the callback you should use for a given situation depends on what you’re trying to accomplish. The best I can do is to serve up some examples to inspire you with your own code.

9.2.5.1 Cleaning Up Attribute Formatting with before_validation on Create

The most common examples of using before_validation callbacks have to do with cleaning up user-entered attributes. For example, the following CreditCard class cleans up its number attribute so that false negatives don’t occur on validation:


1 class CreditCard < ActiveRecord::Base
2   before_validation on: :create do
3     # Strip everything in the number except digits.
4     self.number = number.gsub(/[^0-9]/, "")
5   end
6 end

9.2.5.2 Geocoding with before_save

Assume that you have an application that tracks addresses and has mapping features. Addresses should always be geocoded before saving so that they can be displayed rapidly on a map later.3

As is often the case, the wording of the requirement itself points you in the direction of the before_save callback:


 1 class Address < ActiveRecord::Base
 2
 3   before_save :geocode
 4   validates_presence_of :street, :city, :state, :country
 5   ...
 6
 7   def to_s
 8     [street, city, state, country].compact.join(', ')
 9   end
10
11   protected
12
13   def geocode
14     result = Geocoder.coordinates(to_s)
15     self.latitude = result.first
16     self.longitude = result.last
17   end
18 end

Before we move on, there are a couple of additional considerations. The preceding code works great if the geocoding succeeds, but what if it doesn’t? Do we still want to allow the record to be saved? If not, we should halt the execution chain:


1 def geolocate
2   result = Geocoder.coordinates(to_s)
3   return false if result.empty? # halt execution
4
5   self.latitude = result.first
6   self.longitude = result.last
7 end

The only problem remaining is that we give the rest of our code (and by extension, the end user) no indication of why the chain was halted. Even though we’re not in a validation routine, I think we can put the errors collection to good use here:

 
 1 def geolocate
 2   result = Geocoder.coordinates(to_s)
 3   if result.present?
 4     self.latitude = result.first
 5     self.longitude = result.last
 6   else
 7     errors[:base] << "Geocoding failed. Please check address."
 8     false
 9   end
10 end

If the geocoding fails, we add a base error message (for the whole object) and halt execution so that the record is not saved.

9.2.5.3 Exercise Your Paranoia with before_destroy

What if your application has to handle important kinds of data that, once entered, should never be deleted? Perhaps it would make sense to hook into Active Record’s destroy mechanism and somehow mark the record as deleted instead?

The following example depends on the accounts table having a deleted_at datetime column.


1 class Account < ActiveRecord::Base
2   before_destroy do
3     self.update_attribute(:deleted_at, Time.current)
4     false
5   end
6
7   ...
8 end

After the deleted_at column is populated with the current time, we return false in the callback to halt execution. This ensures that the underlying record is not actually deleted from the database.4

It’s probably worth mentioning that there are ways that Rails allows you to unintentionally circumvent before_destroy callbacks:

  • The delete and delete_all class methods of ActiveRecord::Base are almost identical. They remove rows directly from the database without instantiating the corresponding model instances, which means no callbacks will occur.
  • Model objects in associations defined with the option dependent: :delete_all will be deleted directly from the database when removed from the collection using the association’s clear or delete methods.

9.2.5.4 Cleaning Up Associated Files with after_destroy

Model objects that have files associated with them, such as attachment records and uploaded images, can clean up after themselves when deleted using the after_destroy callback. The following method from Thoughtbot’s Paperclip5 gem is a good example:


1 # Destroys the file. Called in an after_destroy callback.
2 def destroy_attached_files
3   Paperclip.log("Deleting attachments.")
4   each_attachment do |name, attachment|
5     attachment.send(:flush_deletes)
6   end
7 end

9.2.6 Special Callbacks: after_initialize and after_find

The after_initialize callback is invoked whenever a new Active Record model is instantiated (either from scratch or from the database). Having it available prevents you from having to muck around with overriding the actual initialize method.

The after_find callback is invoked whenever Active Record loads a model object from the database and is actually called before after_initialize if both are implemented. Because after_find and after_initialize are called for each object found and instantiated by finders, performance constraints dictate that they can only be added as methods and not via the callback macros.

What if you want to run some code only the first time a model is ever instantiated and not after each database load? There is no native callback for that scenario, but you can do it using the after_initialize callback. Just add a condition that checks to see if it is a new record:


1 after_initialize do
2   if new_record?
3     ...
4   end
5 end

In a number of Rails apps that I’ve written, I’ve found it useful to capture user preferences in a serialized hash associated with the User object. The serialize feature of Active Record models makes this possible, since it transparently persists Ruby object graphs to a text column in the database. Unfortunately, you can’t pass it a default value, so I have to set one myself:


 1 class User < ActiveRecord::Base
 2   serialize :preferences # defaults to nil
 3   ...
 4
 5   protected
 6
 7   def after_initialize
 8     self.preferences ||= Hash.new
 9   end
10 end

Using the after_initialize callback, I can automatically populate the preferences attribute of my user model with an empty hash, so that I never have to worry about it being nil when I access it with code such as user.preferences[:show_help_text] = false.

Ruby’s metaprogramming capabilities combined with the ability to run code whenever a model is loaded using the after_find callback are a powerful mix. Since we’re not done learning about callbacks yet, we’ll come back to uses of after_find later on in the chapter in the section “Modifying Active Record Classes at Runtime.”

9.2.7 Callback Classes

It is common enough to want to reuse callback code for more than one object that Rails provides a way to write callback classes. All you have to do is pass a given callback queue an object that responds to the name of the callback and takes the model object as a parameter.

Here’s our paranoid example from the previous section as a callback class:


1 class MarkDeleted
2   def self.before_destroy(model)
3      model.update_attribute(:deleted_at, Time.current)
4      false
5   end
6 end

The behavior of MarkDeleted is stateless, so I added the callback as a class method. Now you don’t have to instantiate MarkDeleted objects for no good reason. All you do is pass the class to the callback queue for whichever models you want to have the mark-deleted behavior:


1 class Account < ActiveRecord::Base
2   before_destroy MarkDeleted
3   ...
4 end
5
6 class Invoice < ActiveRecord::Base
7   before_destroy MarkDeleted
8   ...
9 end

9.2.7.1 Multiple Callback Methods in One Class

There’s no rule that says you can’t have more than one callback method in a callback class. For example, you might have special audit log requirements to implement:

 1 class Auditor
 2   def initialize(audit_log)
 3     @audit_log = audit_log
 4   end
 5
 6   def after_create(model)
 7     @audit_log.created(model.inspect)
 8   end
 9
10   def after_update(model)
11     @audit_log.updated(model.inspect)
12   end
13
14   def after_destroy(model)
15     @audit_log.destroyed(model.inspect)
16   end
17 end

To add audit logging to an Active Record class, you would do the following:

1 class Account < ActiveRecord::Base
2   after_create Auditor.new(DEFAULT_AUDIT_LOG)
3   after_update Auditor.new(DEFAULT_AUDIT_LOG)
4   after_destroy Auditor.new(DEFAULT_AUDIT_LOG)
5   ...
6 end

Wow, that’s ugly, having to add three Auditors on three lines. We could extract a local variable called auditor, but it would still be repetitive. This might be an opportunity to take advantage of Ruby’s open classes, allowing you to modify classes that aren’t part of your application.

Wouldn’t it be better to simply say acts_as_audited at the top of the model that needs auditing? We can quickly add it to the ActiveRecord::Base class so that it’s available for all our models.

On my projects, the file where “quick and dirty” code like the method in Listing 9.1 would reside is lib/core_ext/active_record_base.rb, but you can put it anywhere you want. You could even make it a plugin.

Listing 9.1 A Quick-and-Dirty acts_as_audited Method


1 class ActiveRecord::Base
2   def self.acts_as_audited(audit_log=DEFAULT_AUDIT_LOG)
3     auditor = Auditor.new(audit_log)
4     after_create auditor
5     after_update auditor
6     after_destroy auditor
7   end
8 end

Now the top of Account is a lot less cluttered:


1 class Account < ActiveRecord::Base
2   acts_as_audited

9.2.7.2 Testability

When you add callback methods to a model class, you pretty much have to test that they’re functioning correctly in conjunction with the model to which they are added. That may or may not be a problem. In contrast, callback classes are easy to test in isolation.


 1 describe '#after_create' do
 2   let(:auditable) { double() }
 3   let(:log) { double() }
 4   let(:content) { 'foo' }
 5
 6   it 'audits a model was created' do
 7     expect(auditable).to receive(:inspect).and_return(content)
 8     expect(log).to receive(:created).and_return(content)
 9     Auditor.new(log).after_create(auditable)
10   end
11 end

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020