skip to content

Table & Attribute Mapping

An Active Record class maps to a table by convention, with table_name, primary_key and the Attributes API to override names, types and defaults. Interviewers check what the schema decides for you.

part ofRuby on Railsread it →
on this pageshow

explore

questions

6

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%

answer

  1. the class body can stay empty
  2. columns read lazily, then cached
  3. reader, writer and ? per column
  4. column defaults seed Model.new
  5. primary_abstract_class: no table of its own

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.

solid answer

~40 s

In Rails' Active Record pattern one object wraps one row, and the row's shape comes from the database, not from the class. The first time a model needs its columns it loads them (names, SQL types, defaults, primary key) from the schema cache or the connection; `column_names` lists them and `type_for_attribute(:due_on)` returns the cast type. Each column gets `due_on`, `due_on=` and `due_on?`, assignment casts values (`"2026-10-01"` becomes a `Date`), `Bill.new` starts from the column defaults, and `id` reads whatever the primary key column is. `created_at` and `updated_at` are filled on save when those columns exist. `ApplicationRecord < ActiveRecord::Base` with `primary_abstract_class` is the app's single abstract base: it has no table, `ApplicationRecord.new` raises `NotImplementedError`, and it holds what every model shares. The schema gives you no validations and no associations; those you still declare.

code

ruby · 14 lines
ruby
class Bill < ApplicationRecord
end

Bill.column_names
# => ["id", "account_no", "amount_cents", "due_on", "status", "created_at", "updated_at"]

bill = Bill.new(due_on: "2026-10-01", amount_cents: "4250")
bill.due_on        # => Wed, 01 Oct 2026 (a Date)
bill.amount_cents  # => 4250 (an Integer)
bill.status        # => "open" (the column default)
bill.amount_cents? # => true

ApplicationRecord.new
# => NotImplementedError: ApplicationRecord is an abstract class and cannot be instantiated.

go deeper

for a junior

Recall that the class body can be empty: columns become typed readers, writers and ? methods, and ApplicationRecord is the abstract base every model inherits.

for a middle

Explain when the schema is loaded and cached, how assignment casts values per column type, and why a running process misses a freshly added column.

for a senior

Show where the schema stops: validations and associations are never inferred, so NOT NULL and foreign keys still need model declarations or the database raises instead of the model.

for a principal

Weigh the trade-off of schema-driven models: fast to change and always in sync with the table, but the class alone no longer documents its own shape.

## The Active Record pattern, as Rails implements it In the **Active Record pattern** an object wraps one database row and carries both the data and the persistence methods (`save`, `destroy`, `find`). Rails' twist is where the row's shape comes from: **the table, not the class**. A model can be as short as this and still be fully usable: ```ruby class Bill < ApplicationRecord end ``` Nothing in the class lists `account_no`, `amount_cents` or `due_on`. Rails finds the `bills` table by convention and asks it what columns it has. ## What the schema gives every model When the class first needs its columns (the first query, the first `Bill.new`, or a call to `column_names`), Active Record **loads the schema**: the column list, each column's SQL type, its default and the table's primary key. It reads them from the **schema cache** or from the connection, then keeps them on the class. From that it builds: - **attribute methods** for every column: a reader (`bill.due_on`), a writer (`bill.due_on = ...`) and a query method (`bill.due_on?`); - **a cast type per column**, so assignment converts input: a `date` column turns `"2026-10-01"` into a `Date`, an `integer` column turns `"42"` into `42`; - **defaults for new records**: `Bill.new.status` returns the column's database default (see `Bill.column_defaults`); - **the primary key** as `id`: `bill.id` reads whatever column the table declares as its key, and `Bill.find(...)` searches on it; - **timestamps**: when `created_at`/`updated_at` (or `created_on`/`updated_on`) columns exist, saves fill them in; - **reflection**: `Bill.column_names`, `Bill.columns`, `Bill.type_for_attribute(:due_on)` and `bill.attributes` (a hash of every attribute). The query methods are worth knowing exactly, because interviewers like the edge cases: | Column type | Value | `attr?` returns | |---|---|---| | boolean | `false` / `nil` | `false` | | integer | `0` | `false` | | integer | `7` | `true` | | string | `" "` (blank) | `false` | | string | `"Paid"` | `true` | Assigning a key that is not an attribute, as in `Bill.new(colour: "red")`, raises `ActiveModel::UnknownAttributeError`. ## When the schema is read, and what that means after a migration The schema is read **lazily** and then **cached on the class**. Two consequences follow: 1. In development, code reloading rebuilds the model classes, so a new column shows up after a migration with no restart. 2. A long-running process that has already loaded `Bill` keeps the old column list. It sees a new column only after a restart, or after `Bill.reset_column_information` (the call migrations use when they write data right after changing a table). ## ApplicationRecord and primary_abstract_class `rails new` generates one base class for every model: ```ruby class ApplicationRecord < ActiveRecord::Base primary_abstract_class end ``` `primary_abstract_class` does two things: it sets `abstract_class = true`, so the class has **no table** and `ApplicationRecord.new` raises `NotImplementedError` ("is an abstract class and cannot be instantiated"), and it registers the class as the application's **primary** abstract class, which Rails treats like `ActiveRecord::Base` when it sets up connections; only one class may claim that. Inheriting from `ApplicationRecord` rather than `ActiveRecord::Base` gives the app one place for shared behaviour (a helper method, a concern included everywhere, a `connects_to` for the primary database) without monkey-patching `ActiveRecord::Base`. ## What the schema does not give you The schema shapes the attributes and nothing else: - a `NOT NULL` column does **not** become a presence validation; - a `customer_id` column does **not** become a `belongs_to` association; - a `CHECK` constraint does **not** become an inclusion validation; - a column you want typed differently, defaulted in Ruby, or an attribute with **no** column, needs the `attribute` macro. So the honest summary is: the table decides **which** attributes exist and how they are cast; the class decides **rules and relationships**. ## Mistakes interviewers listen for - **Declaring columns with `attr_accessor`.** That defines a plain Ruby instance variable that **shadows** the column's attribute methods: the value is never cast, never tracked as a change and never saved. - **Expecting validations from the schema.** A failed `NOT NULL` surfaces as a database exception, not as an entry in `errors`. - **Treating `ApplicationRecord` as a model.** It has no table and no rows; it is shared configuration. - **Forgetting the cache after a migration** in a long-running process such as a job worker. A candidate who can say which of these come from the table and which from the class has understood how Rails' Active Record differs from mappers that declare every field in code.

  • A migration adds a late_fee_cents column, but a long-running worker process says Bill has no such attribute. Why?
    Active Record loads a model's columns once and caches them on the class. A process that loaded `Bill` before the migration keeps the old column list, so `late_fee_cents` is unknown to it until the process restarts or calls `Bill.reset_column_information`. Development hides this because code reloading rebuilds model classes.
  • Does a NOT NULL column on bills.account_no make Active Record validate presence before saving?
    No. The schema only shapes attributes and their types. Without `validates :account_no, presence: true`, `save` sends the INSERT and the database rejects it, which Active Record raises as `ActiveRecord::NotNullViolation` instead of returning `false` with an error on the record.

  • Saying a model must declare each column with attr_accessor before it can be used.
  • Claiming Rails reads the column list on every attribute call instead of caching it on the class.
  • Believing a NOT NULL column automatically adds a presence validation to the model.
  • Thinking a customer_id column creates a belongs_to association without declaring it.
  • Describing ApplicationRecord as a table-backed model that stores shared rows.
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 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, 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 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