skip to content

Active Record Models

Defining and persisting one Active Record model: table mapping, save and finder calls, validations, lifecycle callbacks, enums and normalizers. Interviewers probe what each save path skips.

part ofRuby on Railsread it →
on this pageshow

explore

questions

29

In an Active Record model, in what order do the lifecycle callbacks run when save is called on a new record?

level: juniorimportance: must knowfreq 74%

answer

  1. validation callbacks come first
  2. save chain wraps the create chain
  3. around_save splits at yield
  4. after_save is still inside the transaction
  5. after_commit only after COMMIT

basics

~10 s

Saving a new Active Record object runs before_validation, after_validation, before_save, around_save, before_create, around_create, the INSERT, after_create, after_save, then after_commit once the transaction commits. Updates swap each create hook for its update twin.

solid answer

~40 s

Validation comes first: `before_validation`, the validators, `after_validation`. If the record is valid, the save chain opens with `before_save` and the code before `yield` in `around_save`, then the create chain runs: `before_create`, the first half of `around_create`, the `INSERT`, the rest of `around_create`, and `after_create`. The rest of `around_save` and then `after_save` close the save chain. All of that runs inside the transaction Rails opens for `save`; `after_commit` (or `after_rollback`) runs only when that transaction ends. For a persisted record the same sequence runs with `before_update`, `around_update` and `after_update` in place of the create callbacks. So tidy input in `before_validation`, derive columns in `before_save`, and leave anything the outside world sees for `after_commit`.

code

ruby · 19 lines
ruby
class GymMember < ApplicationRecord
  before_validation { puts "1 before_validation" }
  after_validation  { puts "2 after_validation" }
  before_save       { puts "3 before_save" }
  around_save       :trace_save
  before_create     { puts "5 before_create" }
  after_create      { puts "6 after_create" }
  after_save        { puts "8 after_save" }
  after_commit      { puts "9 after_commit" }

  private
    def trace_save
      puts "4 around_save before yield"
      yield
      puts "7 around_save after yield"
    end
end

GymMember.create!(name: "Ana") # prints 1 to 9 in order

go deeper

for a junior

Recall the order: validation callbacks, then before_save, before_create, the INSERT, after_create, after_save, and after_commit last. Know that updates use the update callbacks instead.

for a middle

Explain why validation runs before before_save, how around callbacks split at yield, and that everything up to after_save shares the save's transaction.

for a senior

Use the order to place work: input cleanup before validation, derived columns before save, and external side effects only after commit, with conditions so no-op saves stay quiet.

for a principal

Weigh how much behaviour a team lets the callback chain own; hidden order dependencies between callbacks are a maintenance cost that explicit service code avoids.

## What a callback is An Active Record **callback** is a method or block that Rails calls at a fixed point in a record's life cycle. You register it with a class macro such as `before_save :set_member_number` or `after_create_commit :send_welcome_sms`. Rails defines nineteen of them in `ActiveRecord::Callbacks`, and the order in which they fire is the first thing an interviewer checks, because it decides what each hook can safely do. ## The chain for a new record Calling `save` (or `create`) on a new `GymMember` runs, in this order: 1. `before_validation` 2. the validators themselves (`validates`, `validate`) 3. `after_validation` 4. `before_save` 5. `around_save`, up to its `yield` 6. `before_create` 7. `around_create`, up to its `yield` 8. the `INSERT` statement 9. the rest of `around_create`, then `after_create` 10. the rest of `around_save`, then `after_save` 11. `after_commit` or `after_rollback`, once the transaction ends Validation runs before any save callback, so a value set in `before_save` is never seen by the validators. If validation fails, `save` returns `false` and none of steps 4-10 run. ## Updates and destroys | Operation | Callbacks, in order | |---|---| | `save` on a new record | validation callbacks, `before_save`, `around_save`, `before_create`, `around_create`, `after_create`, `after_save`, `after_commit` | | `save` / `update` on a persisted record | validation callbacks, `before_save`, `around_save`, `before_update`, `around_update`, `after_update`, `after_save`, `after_commit` | | `destroy` | `before_destroy`, `around_destroy`, `after_destroy`, `after_commit` | The `_create` and `_update` chains are mutually exclusive: a given save runs one or the other, never both. `destroy` runs no validation callbacks at all. ## Around callbacks and the transaction boundary - An `around_*` callback must `yield`; the code before `yield` runs before the wrapped step and the code after it runs once that step and its own callbacks are done. - `save`, `save!` and `destroy` wrap the whole chain, `after_save` and `after_create` included, in one database transaction. Anything those hooks write rolls back if a later step raises. - `after_commit` and `after_rollback` are the only callbacks that run after the transaction has ended, which is why side effects that leave the database belong there. - Several `before_save` or `after_save` callbacks run in the order they are declared. ## Picking the hook - **`before_validation`**: clean user input the validators will check, such as stripping spaces from a phone number. - **`before_save`**: derive a column from other columns on every save, such as a full name. - **`before_create`**: set a value only new rows get, such as a membership number. - **`after_save` / `after_create`**: write related rows that must commit or roll back together with this one. - **`after_commit` variants**: talk to the outside world (SMS, search index, cache, jobs). ## What does not run the chain - `save(validate: false)` skips the validation callbacks but still runs the save and create or update callbacks. - `touch` skips validations and the save chain; it runs only `after_touch`, `after_commit` and `after_rollback`. - Methods that write SQL directly, such as `update_column`, `update_all` and `delete`, skip callbacks entirely; which write method to reach for is a separate topic. ## Three bugs the order explains 1. **A presence validation fails although a callback sets the value.** `validates :member_number, presence: true` together with `before_save :assign_member_number` rejects every new member, because validation runs before `before_save`. Assign the number in `before_validation on: :create`, or drop the validation and assign it in `before_create`. 2. **An SMS describes a member who never existed.** A text sent from `after_save` goes out before `COMMIT`; if anything later raises, the row rolls back but the message is already delivered. Commit callbacks exist for this. 3. **A save inside `after_save` loops.** Calling `save` on `self` from `after_save` re-enters the whole chain, including the same `after_save`. Set the value earlier, in a `before_*` callback, so a single write carries it. ## Inspecting a model's chain When an inherited model or a concern adds callbacks you did not write, list them instead of guessing. Each chain is exposed as `_<name>_callbacks`, so `GymMember._save_callbacks.map { |cb| [cb.kind, cb.filter] }` prints the save chain's kinds and filters. Callbacks declared in a parent class run before the child's, and a `prepend: true` option moves one to the front of its chain. Knowing the order lets you answer the follow-up interviewers like best: why a value set in `before_save` does not satisfy a presence validation, and why an SMS sent from `after_save` can describe a member who never existed.

  • Does save on a persisted record with no changed attributes still run the update callbacks?
    Yes. With nothing changed Rails sends no `UPDATE`, but the save and update chains still run, so `before_save`, `after_update` and `after_save` fire, and `after_update_commit` fires when the transaction finishes. Guard side effects with a condition such as `if: :saved_change_to_phone?` when they should react only to real changes.
  • How does before_validation on: :create differ from before_create?
    `before_validation on: :create` runs only when validation runs for a new record, so `save(validate: false)` skips it, and it runs even when validation then fails. `before_create` runs only after validation passed, right before the `INSERT`, and also runs with `validate: false`. Use the first to tidy input the validators check, the second for values that never come from the user.

  • before_save runs before validation, so it can fix values the validators check
  • after_save runs after COMMIT, so other connections already see the row
  • after_create runs after after_save because creating is the last step
  • Updating a record runs the create callbacks as well as the update ones
  • save(validate: false) skips every callback, not only the validation ones
open as a page

In a Rails 8.1 app, what does an Active Record model inheriting from ApplicationRecord get from its table's schema without declaring any attributes?

level: juniorimportance: must knowfreq 72%

basics

~20 s

Active Record reads the table's columns when the class first needs them and defines a typed reader, writer and ? method for each, seeds new records with column defaults and treats the primary key as id; ApplicationRecord itself is abstract and has no table.

open as a page

In Active Record, what do save, create and update return when a record is invalid, and how do save!, create! and update! differ?

level: juniorimportance: must knowfreq 85%

basics

~10 s

save and update return false and fill errors; create returns the object unsaved, with errors. The bang versions raise ActiveRecord::RecordInvalid for failed validations and ActiveRecord::RecordNotSaved when a before callback aborts.

open as a page

In a Rails 8.1 Order model, what does enum :status, { placed: 0, baking: 1, out_for_delivery: 2, delivered: 3 } give you?

level: juniorimportance: must knowfreq 64%

basics

~20 s

An integer status column read and written by name: order.status returns "baking", baking? and baking! check and save a value, Order.baking and Order.not_baking are scopes, and Order.statuses holds the label-to-integer map. Unknown values raise ArgumentError.

open as a page

In an Active Record model, when do validations run, and how does a failed validation stop a save and report why?

level: juniorimportance: must knowfreq 82%

basics

~20 s

save, save!, create, update and their bang forms call valid? before writing; valid? clears errors, runs every validation for the :create or :update context, and any error stops the write, with the reasons left in record.errors.

open as a page

In an Active Record model, why should a gym member's welcome SMS and search-index sync go in after_create_commit and after_save_commit rather than after_save?

level: middleimportance: must knowfreq 66%

basics

~20 s

Rails runs after_create and after_save inside the save's transaction, before COMMIT, so a later failure can roll the row back after the SMS went out. The commit variants run only once the outermost transaction has committed and the row is visible.

open as a page

In Rails 8.1, what do update, update_column(s), update_all and touch each skip among validations, callbacks and updated_at?

level: middleimportance: must knowfreq 75%

basics

~10 s

update runs validations, callbacks and bumps updated_at. update_column(s) and update_all skip validations, callbacks and updated_at (update_column accepts touch: true since 8.1); touch skips validations and runs only after_touch and commit callbacks.

open as a page

In a Rails 8.1 model, how do enum declarations with an array, an integer hash and a string hash differ, and which fits?

level: middleimportance: must knowfreq 50%

basics

~20 s

An array maps labels to integers by position, so inserting or removing a label silently remaps stored rows. An integer hash pins each value, and a string hash stores the label text. Prefer a hash; use strings when people read the table.

open as a page

Why can validates :username, uniqueness: true still let two players register the same username, and how do you close the gap in a Rails app?

level: seniorimportance: must knowfreq 65%

basics

~20 s

The validator runs a SELECT and the save runs a later INSERT, so two concurrent requests can both find no row and both insert. A unique index makes the second INSERT fail with ActiveRecord::RecordNotUnique, which the app rescues into a :taken error.

open as a page

In Active Record, how would you map a Customer model onto a legacy tbl_customers table keyed by account_no, with columns like cust_nm?

level: juniorimportance: should knowfreq 55%

basics

~10 s

Set self.table_name = "tbl_customers", set self.primary_key = "account_no" if the table declares no key, and add alias_attribute :name, :cust_nm; then find, id and URLs use account_no and the aliases work in where and order.

open as a page

In Active Record, what do find, find_by and find_by! do when no matching row exists, and when do you choose each?

level: juniorimportance: should knowfreq 68%

basics

~10 s

find looks up by primary key and raises ActiveRecord::RecordNotFound when it is missing; find_by takes any conditions and returns nil; find_by! takes conditions but raises RecordNotFound like find.

open as a page

In an Active Record model, what happens when a before callback calls throw :abort, and what do save, save!, destroy and destroy! return?

level: middleimportance: should knowfreq 52%

basics

~10 s

Calling throw :abort in before_save, before_create, before_update or before_destroy cancels the later callbacks and the SQL, and the transaction rolls back. save and destroy return false; save! raises ActiveRecord::RecordNotSaved and destroy! raises ActiveRecord::RecordNotDestroyed.

open as a page

In an Active Record model, what does attribute :name, :type, default: change for an existing column, and what happens when no column backs it?

level: middleimportance: should knowfreq 45%

basics

~20 s

Over a column, attribute replaces the type the schema inferred and, with default:, the column's default for new records. Without a column it adds a typed, defaulted virtual attribute that casts input and appears in attributes but is never written to the table.

open as a page

In Active Record, when are created_at and updated_at filled in, and how do you save a change without moving updated_at?

level: middleimportance: should knowfreq 40%

basics

~10 s

Active Record writes created_at and updated_at itself when those columns exist: both on insert, and updated_at on an update that has changes to save. save(touch: false) or record_timestamps = false saves without moving updated_at.

open as a page

In Active Record, how do destroy and delete differ, and when would you use destroy_all versus delete_all to purge listings?

level: middleimportance: should knowfreq 70%

basics

~20 s

destroy loads the record's callbacks and dependent: associations before deleting and can be stopped; delete sends one DELETE with no callbacks. destroy_all destroys each loaded record; delete_all issues a single DELETE and returns the row count.

open as a page

In a Rails 8.1 model, what do enum's prefix:, suffix:, scopes:, instance_methods: and validate: options change?

level: middleimportance: should knowfreq 34%

basics

~20 s

prefix: and suffix: rename the generated predicates, bang methods and scopes so labels shared by two enums do not clash; scopes: false and instance_methods: false skip generating those; validate: true turns an unknown value into a validation error instead of ArgumentError.

open as a page

In a Rails 8.1 model, how does normalizes :phone behave on assignment, in where and find_by queries, for nil, and for rows saved earlier?

level: middleimportance: should knowfreq 42%

basics

~20 s

normalizes runs its with: callable whenever the attribute is assigned and on query values in where, find_by and exists? hash conditions, but not in raw SQL strings. nil is skipped unless apply_to_nil: true, and rows saved before the declaration stay raw until reassigned.

open as a page

In a Rails youth-sports Player model, which built-in validators enforce a username format and an age from 6 to 18, and what traps hide in them?

level: middleimportance: should knowfreq 55%

basics

~20 s

Use format: { with: /\A[a-z0-9_]+\z/ } and length: { in: 3..20 } for the username, numericality: { only_integer: true, in: 6..18 } for age, and comparison: for dates; ^ or $ in a format regex raises, and presence rejects false.

open as a page

In Rails, when do you write validate :method, a validates_with validator class or an ActiveModel::EachValidator, and how does each add errors?

level: middleimportance: should knowfreq 50%

basics

~20 s

Use validate :method for a rule specific to one model, an ActiveModel::EachValidator for a per-attribute rule reused through validates :attr, name: true, and an ActiveModel::Validator with validates_with for whole-record rules; all add messages with record.errors.add.

open as a page

In an Active Record model, how do on: :create, a custom context like on: :registration, and if: control when a validation runs?

level: middleimportance: should knowfreq 42%

basics

~20 s

on: limits a validation to a context: :create for new records, :update for persisted ones, or a custom name passed as valid?(:registration) or save(context: :registration). if: and unless: add a runtime condition from a method name or lambda.

open as a page

In Active Record, what do scope: and case_sensitive: change in validates :username, uniqueness:, and what query does the check run?

level: middleimportance: should knowfreq 60%

basics

~20 s

uniqueness runs SELECT 1 ... LIMIT 1 for another row with the same value (excluding the record itself); scope: adds equality conditions on other columns, and case_sensitive: false compares with LOWER() instead of the column's collation.

open as a page

In a Rails 8.1 model declaring after_create_commit :sync_index and after_update_commit :sync_index, why does a newly created gym member never get indexed?

level: seniorimportance: should knowfreq 38%

basics

~10 s

Both macros register after_commit :sync_index, and Rails keeps one callback per filter, so the update-only declaration replaces the create one. Use after_save_commit :sync_index, or after_commit :sync_index, on: [:create, :update].

open as a page

In Active Record, why does attribute :paperless, :boolean misread a legacy CHAR(1) 'Y'/'N' column, and how would a custom type fix it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

Active Model's Boolean type treats only values like false, 0, "0", "f" and "false" as false, so "N" casts to true. A custom ActiveRecord::Type::Value that casts "Y"/"N" to booleans and serializes them back keeps reads, writes and where in step.

open as a page

In Active Record, how do changed?, saved_change_to_price? and previous_changes differ before and after a save, and which belongs in after_save code?

level: seniorimportance: should knowfreq 50%

basics

~10 s

changed? and price_changed? describe edits not yet saved; once the row is written they are cleared. saved_change_to_price?, saved_changes and previous_changes describe what the last save wrote, so after_save and after_commit code reads those.

open as a page

In a Rails classified-ads app, why does listing.update(views_count: listing.views_count + 1) lose views under load, and what should bump the counter instead?

level: seniorimportance: should knowfreq 40%

basics

~20 s

update computes the new count in Ruby and writes it as a literal, so concurrent requests overwrite each other. increment!(:views_count) or Listing.update_counters(id, views_count: 1) sends views_count = COALESCE(views_count, 0) + 1, which the database applies atomically.

open as a page

In a Rails 8.1 model, when do you reach for serialize, store or store_accessor, and why must serialize name its coder?

level: seniorimportance: should knowfreq 30%

basics

~20 s

serialize keeps one Ruby value in a text column through a coder, which load_defaults 7.1 and later make mandatory; store wraps serialize for a hash with named accessors; store_accessor adds accessors to a native JSON column or existing store without another serializer.

open as a page

In an Active Record model, when do after_initialize, after_find and after_touch run, and why is after_initialize costly on large queries?

level: middleimportance: nice to knowfreq 24%

basics

~20 s

after_initialize runs for every object Active Record builds, through new, a finder or dup; after_find runs just before it for loaded rows only; after_touch runs on touch. Since after_initialize fires per row, any work there multiplies across large results.

open as a page

In a Rails 8.1 model, what happens when code changes an attr_readonly attribute such as order_number on a persisted record?

level: middleimportance: nice to knowfreq 16%

basics

~20 s

With load_defaults 7.1 or later, assigning a new value to an attr_readonly attribute of a persisted record raises ActiveRecord::ReadonlyAttributeError. On older defaults the value changed in memory but was silently left out of the UPDATE.

open as a page

In Rails 8.1, how does an Active Record model work with a composite primary key such as [:account_no, :invoice_no], and what changes for find and id?

level: seniorimportance: nice to knowfreq 20%

basics

~20 s

Since Rails 7.1 Active Record reads a composite key from the table, or takes self.primary_key = [:account_no, :invoice_no]; find then takes an array of values, id returns an array, and to_param joins the parts with an underscore.

open as a page