Skip to the workspace
Pebellslearn by building
Models  ›  Capstone Project

Model Callbacks and Model Methods

Callbacks 15 minModel methods put behaviour next to the data it uses, and callbacks such as before_validation, before_save and after_create_commit run code automatically at fixed points in a record's life.

ruby on rails / Model Callbacks and Model Methods

Explore each scene at your own pace.

01 · The rule

The rule

Model Callbacks and Model Methods

Models are not just rows. A book can tell you its average rating; a review can tidy its own text before it is checked. Model methods hold that behaviour. Callbacks are a special kind: methods Rails calls for you at fixed moments, such as just before saving.

The rule

Ask the model, not the controller; hook the moment, not every save.

Model methods are ordinary Ruby methods:

class Book < ApplicationRecord
  has_many :reviews, dependent: :destroy

  def average_rating
    reviews.average(:rating)&.round(1)       # nil when there are no reviews
  end

  def long?
    pages.to_i > 500
  end

  def self.by(author)                       # class method: Book.by("Le Guin")
    where(author: author)
  end
end

Now views and controllers say @book.average_rating instead of repeating the calculation.

Callbacks run at points in the life of a record. For a new record that is saved, the order is:

  1. before_validation → validations → after_validation
  2. before_save → before_create → INSERT → after_create → after_save
  3. after_commit (here after_create_commit) — once the transaction is really done

Updates use before_update / after_update; deletes use before_destroy / after_destroy.

class Book < ApplicationRecord
  before_validation :tidy_title
  after_create_commit :notify_followers

  private

  def tidy_title
    self.title = title.to_s.squish
  end

  def notify_followers
    NewBookMailer.with(book: self).announce.deliver_later
  end
end

Rails 7.1 added a neater way for the first job: normalizes :title, with: -> title { title.squish }.

To stop a save from a before_ callback, call throw :abort.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.