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?
answer
- the class body can stay empty
- columns read lazily, then cached
- reader, writer and ? per column
- column defaults seed Model.new
- primary_abstract_class: no table of its own
basics
~20 sActive 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 sIn 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 linesclass 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
Recall that the class body can be empty: columns become typed readers, writers and ? methods, and ApplicationRecord is the abstract base every model inherits.
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.
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.
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.