skip to content

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%

answer

  1. only if the columns exist
  2. _at or _on names, aliases honoured
  3. insert sets both, unless already set
  4. update bumps only with changes
  5. save(touch: false), record_timestamps

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.

solid answer

~40 s

Timestamping is driven by column names: `created_at`/`created_on` and `updated_at`/`updated_on`, resolved through `alias_attribute`, so a legacy `created_dt` aliased to `created_at` works too. On **insert** every timestamp column present is set to the current time unless the code already assigned it. On **update**, `updated_at` is bumped only when the record has changes to save (a `save` with nothing changed issues no UPDATE), and not when the change set already includes `updated_at`. Times come from `Time.now.utc` by default and read back in `Time.zone`. To save without moving `updated_at`, call `save(touch: false)` for one save, or set `self.record_timestamps = false` on the class to switch it off for that model. `dup` clears both timestamps on the copy.

code

ruby · 10 lines
ruby
reading = MeterReading.create!(meter_id: 7, kwh: 412)
reading.created_at == reading.updated_at # => true

reading.save                    # nothing changed: no UPDATE, updated_at unchanged

reading.kwh = 415
reading.save(touch: false)      # kwh written, updated_at kept

reading.kwh = 418
reading.save                    # kwh written, updated_at bumped

go deeper

for a junior

Recall that created_at and updated_at are maintained automatically when the columns exist, with no code in the model.

for a middle

Explain the insert and update rules: explicit values kept, no bump without changes, and save(touch: false) versus record_timestamps.

for a senior

Protect updated_at semantics in bulk recalculations and imports, because caches and sync feeds key off it.

for a principal

Decide whether updated_at should mean any write or a meaningful edit, and make background jobs follow that rule consistently.

## Timestamps are a naming convention Active Record does not need any declaration to maintain timestamps. It looks at the table's columns and treats four names specially: - **create timestamps**: `created_at` and `created_on`; - **update timestamps**: `updated_at` and `updated_on`. The names are resolved through the model's **attribute aliases**, so a legacy billing table with `created_dt` and `changed_dt` can join in: ```ruby class Customer < ApplicationRecord self.table_name = "tbl_customers" alias_attribute :created_at, :created_dt alias_attribute :updated_at, :changed_dt end ``` If none of these columns exist, nothing happens and nothing fails. ## On insert When a new record is created, Active Record takes the current time once and writes it to **every** timestamp column present, both create and update ones, **unless the attribute already has a value**. So `MeterReading.create!(created_at: 2.days.ago, ...)` keeps the time you gave it, which is what imports and backfills rely on. ## On update An update bumps `updated_at`/`updated_on` only when three things hold: 1. `record_timestamps` is on for the class (the default); 2. the save was not called with `touch: false`; 3. the record **has changes to save**. With partial updates (the default), a `save` on an unchanged record sends no UPDATE and leaves `updated_at` alone. And for each update timestamp column, if your own change set already includes it (`customer.updated_at = ...`), Active Record leaves your value in place. ## Saving without moving updated_at | Need | Tool | Scope | |---|---|---| | one save that must not bump `updated_at` | `record.save(touch: false)` | that call | | a model that should never be stamped | `self.record_timestamps = false` | the class | | every model in the app | `config.active_record.record_timestamps = false` | global, rarely right | `save(touch: false)` still runs validations and callbacks and still writes the changed columns; only the update timestamp is skipped, and only on updates, since a new record is stamped regardless. Typical use: a nightly job that recalculates a cached balance on each customer and should not make every record look edited by a person. ## Time and time zones - Timestamps are taken with `Time.now.utc` when `ActiveRecord.default_timezone` is `:utc` (the default) and `Time.now` when it is `:local`. - Datetime columns are **time-zone aware**: stored in UTC and read back converted to `Time.zone`, the app's `config.time_zone`. ## Other places timestamps behave differently - `dup` returns a new, unsaved copy with the timestamps **cleared**, so they are set afresh when the copy is saved. - Methods that skip the save path entirely (bulk SQL updates, single-column writes and the touch helpers) follow their own rules; those belong to the create/update/destroy topic. - The migration helper that adds the two columns, and their `NOT NULL` constraint, belongs to migrations. ## Why interviewers care `updated_at` feeds cache versions, sync jobs and "recently changed" screens. A bulk recalculation that stamps every row can invalidate caches and flood sync feeds, while a save path that skips stamping by accident makes stale data look fresh. Knowing exactly when the stamp moves is the point of the question. ## Mistakes interviewers listen for - **Adding a `before_create` callback to set `created_at`.** It duplicates what Active Record already does and can fight with imported values. - **Assuming a save always means a new `updated_at`.** A save with no changes writes nothing. - **Switching off `record_timestamps` globally** to fix one job. That hides real edits everywhere; `save(touch: false)` keeps the change local. - **Expecting `touch: false` to skip stamping a new record.** It only affects updates; an insert is stamped whenever `record_timestamps` is on. - **Forgetting legacy names.** A table with `created_dt` silently gets no timestamps until the column is aliased. Getting these right is what separates "Rails fills in the timestamps" from knowing exactly when, and when not.

  • An import calls Customer.create!(created_at: Time.utc(2019, 3, 1), ...). Does Active Record overwrite created_at with the current time?
    No. On insert Active Record fills a timestamp column only when the attribute is still empty, so an explicitly assigned `created_at` is kept. `updated_at`, if left unassigned, is still set to the current time.
  • A legacy table names its columns created_dt and changed_dt. How do you get automatic timestamps without renaming them?
    Alias them: `alias_attribute :created_at, :created_dt` and `alias_attribute :updated_at, :changed_dt`. Active Record resolves its timestamp names through the alias table, so inserts and updates then stamp the legacy columns.

  • Claiming every save bumps updated_at, even when no attribute changed.
  • Saying created_at must be set in a before_create callback for each model.
  • Believing save(touch: false) also skips validations and callbacks.
  • Expecting Active Record to overwrite a created_at value the code assigned explicitly.
  • Thinking timestamps are stored in the app's config.time_zone instead of UTC.