In an Active Record model, when do after_initialize, after_find and after_touch run, and why is after_initialize costly on large queries?
answer
- three after-only callbacks
- after_find before after_initialize
- new, loaded rows and dup
- MissingAttributeError on partial selects
- touch runs after_touch and commit hooks
basics
~20 safter_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.
solid answer
~40 sThese three are after-only callbacks; Rails defines no `before_` or `around_` versions. `after_initialize` fires whenever an object is built: `GymMember.new`, every row a finder loads, and `dup`. `after_find` fires only for rows loaded from the database, and before `after_initialize`. `after_touch` fires when `touch` updates timestamps; `touch` skips validations and the save chain and runs only `after_touch`, `after_commit` and `after_rollback`. The cost: `GymMember.where(active: true).to_a` returning 20,000 rows runs `after_initialize` 20,000 times, so a query or an expensive computation inside it becomes 20,000 of them. It also breaks partial selects: reading a column that `select(:id)` left out raises `ActiveModel::MissingAttributeError`. Guard such hooks with `if: :new_record?`, or set defaults with the Attributes API instead.
code
ruby · 14 linesclass GymMember < ApplicationRecord
after_initialize :set_default_tier, if: :new_record?
after_find { Rails.logger.debug("loaded member #{id}") }
after_touch { Rails.logger.info("activity for #{id}") }
private
def set_default_tier
self.plan_tier ||= "basic"
end
end
GymMember.new.plan_tier # => "basic"
GymMember.select(:id).first # fine: guard skips loaded rows
GymMember.first.touch # runs after_touch, then after_commitgo deeper
Know which action triggers each callback: new or a finder for after_initialize, a finder for after_find, and touch for after_touch.
Explain the load order, after_find then after_initialize, and why touch runs only after_touch and the commit callbacks.
Recognise the per-row cost and the MissingAttributeError on partial selects, and replace unguarded after_initialize defaults with guarded or declarative ones.
Treat per-object hooks as a hidden tax on every query, and set a rule for where defaults and derived values live so list pages stay predictable.
## Three after-only callbacks Most Active Record callbacks come in `before_`, `around_` and `after_` versions. Three do not: Rails declares `define_model_callbacks :initialize, :find, :touch, only: :after`, so only `after_initialize`, `after_find` and `after_touch` exist. They hook the moments an object comes into existence or has its timestamps bumped, rather than a write of its attributes. ## When each one fires | Trigger | `after_find` | `after_initialize` | `after_touch` | |---|---|---|---| | `GymMember.new(...)` | no | yes | no | | `GymMember.find(1)`, `find_by`, `first`, iterating a relation | yes, first | yes, second | no | | `member.dup` | no | yes | no | | `member.touch` | no | no | yes | For a loaded row, `after_find` runs and then `after_initialize`. Every finder that instantiates records triggers both: `find`, `find_by`, `first`, `last`, `take`, `sole`, `all` once loaded, `find_by_sql` and the rest. ## The cost on large result sets `after_initialize` is a per-object hook, so its price scales with every query in the app: - **Multiplication.** A list page that loads 500 members runs the callback 500 times. A database call inside it turns one page load into 501 queries. - **Partial selects break.** `GymMember.select(:id, :name)` builds objects without the other columns. If the callback reads `plan_tier`, Rails raises `ActiveModel::MissingAttributeError`. - **Defaults overwrite data.** A callback such as `self.plan_tier = "basic"` runs for loaded rows too, so it overwrites real values in memory unless guarded. Safer patterns: 1. Guard the hook: `after_initialize :set_defaults, if: :new_record?`. 2. Check presence when it must run for loaded rows: `has_attribute?(:plan_tier)`. 3. Prefer a declarative default on the attribute itself for plain values, which costs nothing per row and is a topic of its own. ## touch and after_touch `member.touch` writes `updated_at` (and any extra columns you name) directly, without validations and without `before_save` or `after_save`. Its callbacks are deliberately few: - `after_touch` runs once the timestamp is written, - `after_commit` and `after_rollback` run when its transaction ends, - `touch` raises `ActiveRecord::ActiveRecordError` on a new record, which has no row to touch. `after_touch` is useful for cache keys and denormalised "last activity" fields. Touches can also propagate from a child to its parent through an association option, which belongs to association configuration rather than to callbacks. ## after_find in practice `after_find` is rarer still. It suits work that only makes sense for persisted data, such as decrypting or decoding a legacy column into an instance variable, or counting loads while profiling. The same per-row cost applies, and it runs before `after_initialize`, so a value it prepares is available to that callback. For most derived values a plain reader method computed on demand is cheaper, because it runs only when something asks for the value. ## Where these sit next to the save chain None of the three is part of `save`. A record built with `new` and then saved runs `after_initialize` once, at build time, and then the normal validation and save chain. Even `reload` is worth a thought: it fetches the row through a finder into a fresh internal object and copies its attributes across, so the load callbacks run for that fresh object. Keep that separation in mind when an interviewer asks which callback runs "when a record is loaded and saved again": `after_find` and `after_initialize` at load, the save chain at save. ## Common misuse - Using `after_initialize` to send notifications or enqueue jobs: it fires on every load, so a report page could trigger thousands. - Using it to normalise input: assignment-time normalisation belongs elsewhere, because the callback never sees later assignments. - Forgetting `dup`: a copied member runs `after_initialize` again, which can reset values the copy was meant to keep. ## How to reason about these in an interview - Name the trigger precisely: built, found, or touched. - Mention the order on loads: `after_find`, then `after_initialize`. - Explain the per-row cost and the partial-select failure. - Offer the safer alternative instead of saying never. These callbacks are niche, but the partial-select crash and the per-row cost are the two production stories interviewers look for.
- Why does an after_initialize that reads a column fail on GymMember.select(:id).first?`select(:id)` loads objects that hold only `id`. The callback runs for each of them, and reading an attribute that was not selected raises `ActiveModel::MissingAttributeError`. Guard the callback with `if: :new_record?` or check `has_attribute?` before reading.
- after_find also runs for objects built with new
- after_initialize runs once per query, not once per loaded record
- touch runs validations and the before_save callbacks
- Partial selects skip after_initialize, so reading any column there is safe