Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 37 ยท Forms, Validation and Callbacks

Callbacks and Form Objects

Learn Active Record callbacks (before_validation, before_save, after_commit and more), their order, the traps of side effects, and how form objects with ActiveModel keep complex forms clean. Runnable stand-ins.

An Active Record object goes through a life: it is built, validated, saved, updated and finally destroyed. Callbacks let you hook your own code into those moments: normalize an email before validation, generate a slug before saving, send a welcome email after creation. Used for small, local tasks they are neat. Used for everything, they turn a model into a tangle where saving one record triggers a hidden chain of side effects.

This lesson shows the callbacks, their order, which ones to prefer, and the patterns that replace them when they get heavy: normalizes, service objects and form objects. Rails code is read-only here; the runnable stand-ins imitate the lifecycle.

The callback list

For creating a record, the order is:

TEXT
before_validation
after_validation
before_save
around_save
before_create
around_create
after_create
after_save
after_commit  (or after_rollback)

Updating uses before_update / after_update instead of the create pair; before_destroy and after_destroy run when you destroy. after_initialize and after_find fire when an object is built or loaded.

Ruby
class Post < ApplicationRecord
  before_validation :normalize_title
  before_save :generate_slug, if: :title_changed?
  after_create_commit :notify_followers

  private

  def normalize_title = self.title = title.to_s.strip.squeeze(" ")
  def generate_slug = self.slug = title.parameterize
  def notify_followers = NotifyFollowersJob.perform_later(self)
end

If a before_* callback throws :abort, Rails stops the chain and the save returns false. (Returning false no longer halts since Rails 5.) A callback that raises an exception rolls the whole transaction back.

Ruby Stand-in: a callback chain

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

after_commit, not after_save, for side effects

A transaction wraps save. If you send an email or enqueue a job in after_save, the job might run before the transaction commits and look for a row that is not there yet, or run for a record that then gets rolled back. after_commit (and after_create_commit, after_update_commit, after_destroy_commit) fire only once the data is truly stored. Use them for anything that talks to the outside world: emails, jobs, webhooks, search indexing, cache clearing.

Conditions and skipping

Ruby
before_save :normalize_phone, if: :phone_changed?
after_update :audit, unless: -> { saved_changes.empty? }

You can skip some callbacks per call: update_column, update_columns, update_all, delete, delete_all, touch and insert_all bypass callbacks or validations. This is useful for data fixes and dangerous when you forget it.

Dirty tracking helps: in a before_ callback use title_changed?, title_was; in an after_ callback use saved_change_to_title? and saved_changes.

Prefer normalizes, generates_token_for and defaults

Several old callback jobs now have dedicated tools:

Ruby
class User < ApplicationRecord
  normalizes :email, with: ->(email) { email.strip.downcase }   # runs on assign, and on find_by
  generates_token_for :password_reset, expires_in: 15.minutes do
    password_salt.last(10)
  end
  attribute :status, :string, default: "draft"                   # instead of after_initialize
end

normalizes also applies to User.find_by(email: " [email protected] "), which a callback cannot do. Reach for these before writing a callback.

The trouble with callbacks

Callbacks run every time, in every context: console, seeds, tests, imports. The danger signs:

  • A callback calls another model's save, which has callbacks of its own (a hidden chain).
  • An after_save sends an email, so creating 10,000 imported users sends 10,000 emails.
  • Tests become slow or need stubbing because every record creation does real work.
  • The order of declaration matters and nobody remembers it.

A good rule: callbacks are fine to fix up the model's own data (normalize, default, compute a slug) and for tiny, reliable reactions (after_commit enqueue a job). Business workflows ("sign-up: create the user, create a team, send a welcome mail, start a trial") belong in a plain Ruby object you call explicitly.

Service objects

Ruby
class SignUp
  def initialize(params) = @params = params

  def call
    ActiveRecord::Base.transaction do
      user = User.create!(@params.slice(:name, :email, :password))
      team = Team.create!(name: "#{user.name}'s team", owner: user)
      user.update!(team: team)
      WelcomeMailer.with(user: user).welcome.deliver_later
      user
    end
  end
end

The workflow is visible in one place and testable without relying on hidden callbacks. Rails does not mandate a folder; many teams use app/services or app/models for plain objects.

Form objects with ActiveModel

Sometimes one form edits several models, or the form's shape does not match a table: a registration form with a terms checkbox that creates a user and a profile. A form object is a plain class that quacks like a model, so form_with and validations work, but it is not tied to one table.

Ruby
class RegistrationForm
  include ActiveModel::Model
  include ActiveModel::Attributes

  attribute :name, :string
  attribute :email, :string
  attribute :terms, :boolean

  validates :name, :email, presence: true
  validates :terms, acceptance: true

  def save
    return false unless valid?
    ActiveRecord::Base.transaction do
      user = User.create!(name: name, email: email)
      Profile.create!(user: user)
    end
    true
  end
end

In the controller: @form = RegistrationForm.new(params.expect(registration: [:name, :email, :terms])), and form_with model: @form, url: registrations_path. You get the same errors, labels and param names as with a model.

Ruby Stand-in: a form object with validation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

A good test of whether you need a form object: does the form create or update more than one record, or ask for data that is not a column? If yes, use one. If it maps cleanly to one model, plain form_with model: is simpler.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should you enqueue a background job that needs the saved row to exist?

    after_commit runs after the transaction is committed, so the row is visible to other processes.
  2. 2. How does a before_save callback stop the save?

    Since Rails 5 only throw :abort halts the chain; returning false does nothing special.
  3. 3. Which method skips callbacks and validations?

    update_columns writes straight to the database; so do update_all, delete_all and touch.
  4. 4. When is a form object a good idea?

    Form objects model the form itself and can create several records in one transaction.

Summary

  • Callbacks hook into validation, save, create, update and destroy; throw :abort halts a chain.
  • Use after_commit for side effects that leave the database (jobs, emails, webhooks).
  • Prefer normalizes, attribute defaults and generates_token_for to hand-written callbacks.
  • Keep callbacks for the model's own data; move workflows to service objects.
  • Form objects (ActiveModel::Model) give multi-model or virtual-field forms validations and form_with support.

Next: Authentication with has_secure_password