---
title: Models
description: "A Model describes one table, reads its attributes from your migrations, and declares only behavior."
seo:
  description: "Define Active Record Models on ApplicationRecord, with attributes from your migrations, overrides, table names, building records, permit, ids, and timestamps."
---

## At a glance

| To                                   | Write                                                           |
| ------------------------------------ | --------------------------------------------------------------- |
| define a Model                       | `class Product extends ApplicationRecord {}`                    |
| read a column as another type        | `static override attributes = { archived: "boolean" } as const` |
| ignore a column                      | `static override attributes = { legacyNotes: false } as const`  |
| add an attribute that isn’t a column | `termsOfService: { type: "boolean", virtual: true }`            |
| normalize a value as it’s assigned   | `this.normalizes("email", { with: (email) => email.trim() })`   |
| give an attribute another name       | `title: { aliasOf: "name" }`                                    |
| type an attribute more narrowly      | `declare status: "draft" \| "published"`                        |
| use another table name               | `static override table = "billing_accounts"`                    |
| declare attributes for a view        | `class ProductCount extends ApplicationRecord.define({ … }) {}` |
| build a record without saving it     | `Product.build({ name: "Lamp" })`, never `new Product()`        |
| take only some fields from a request | `Product.permit(await request.json(), "name", "metadata")`      |

| Prop | Type | Default | Description |
| - | - | - | - |
| `with` | `(value) => value` | - | The function `normalizes` runs. It takes a value already cast to the attribute’s type, and returns the one to keep. |
| `applyToNull?` | `boolean` | `false` | Hands `null` to `normalizes`’s `with` too. By default, `null` is kept as it is. |

Each part of a Model has a page of its own:

| To                                         | See                                  |
| ------------------------------------------ | ------------------------------------ |
| learn each type, and how values are cast   | [Attribute types](/attribute-types) |
| give an attribute a fixed set of names     | [Enums](/enums)                     |
| see what changed before and after a save   | [Change tracking](/change-tracking) |
| send records as JSON, and keep secrets out | [Serialization](/serialization)     |
| check records before they’re saved         | [Validations](/validations)         |
| run code as records are saved              | [Callbacks](/callbacks)             |
| share behavior across every Model          | [Shared behavior](/shared-behavior) |

## The Models

The examples use these Models, whose attributes come from their tables through the schema `active-record schema` generates:

```ts product.ts
import { ApplicationRecord } from "./application-record";

export class Product extends ApplicationRecord {
  static override attributes = {
    archived: { type: "boolean", default: () => false }, // 0 or 1 in a plain INTEGER column
    metadata: "json", // JSON in a plain TEXT column
    legacyNotes: false, // a column this app no longer uses: never read or written
    publicId: { generateId: true }, // generated in code, as a TEXT key is
    title: { aliasOf: "name" }, // another name for name, in queries too
  } as const;

  declare status: "draft" | "published"; // narrower than the column's string
}
```

```ts featured-product.ts
import { Product } from "./product";

export class FeaturedProduct extends Product {} // shares products, and Product's declarations
```

```ts account.ts
import { ApplicationRecord } from "./application-record";

export class Account extends ApplicationRecord {
  static override table = "billing_accounts"; // in place of accounts
  static override attributes = {
    termsOfService: { type: "boolean", virtual: true }, // a form's checkbox, never a column
  } as const;

  static {
    this.normalizes("email", { with: (email) => email.trim().toLowerCase() });
  }
}
```

```ts product-count.ts
import { ApplicationRecord } from "./application-record";

// A view, which migrations don't describe, so the Model declares its attributes itself:
export class ProductCount extends ApplicationRecord.define({
  status: { type: "string", null: false },
  total: { type: "integer", null: false },
}) {
  static override table = "product_counts";
  static override primaryKey = "status";
}
```

```ts application-record.ts
import { Model } from "@forestfuture/active-record";
import { schema } from "../db/schema";

export abstract class ApplicationRecord extends Model {
  static override schema = schema;
}
```

```ts schema.ts
// Generated by `active-record schema` from migrations/ — don't edit.
// schema: e02b5fa3d693

import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
import { d1 } from "@forestfuture/active-record/d1";

/** billing_accounts — last changed by 0001_create_tables.sql */
export const billingAccounts = {
  id: { type: "string", null: false, generateId: true },
  email: { type: "string", null: false },
} as const;

/** products — last changed by 0001_create_tables.sql */
export const products = {
  id: { type: "string", null: false, generateId: true },
  publicId: "string",
  name: { type: "string", null: false },
  status: { type: "string", null: false, default: () => "draft" },
  archived: { type: "integer", null: false, default: () => 0 },
  metadata: "string",
  legacyNotes: "string",
  createdAt: { type: "datetime", null: false },
  updatedAt: { type: "datetime", null: false },
} as const;

/** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */
export const schema = defineSchema({
  adapter: d1({ binding: "DB" }),
  tables: {
    billing_accounts: { attributes: billingAccounts, primaryKey: "id" },
    products: { attributes: products, primaryKey: "id" },
  },
  models: { Account: "billing_accounts", Product: "products" },
});

declare module "../models/account" {
  interface Account
    extends TableAttributes<typeof billingAccounts, (typeof Account)["attributes"]> {}
}

declare module "../models/product" {
  interface Product extends TableAttributes<typeof products, (typeof Product)["attributes"]> {}
}
```

```sql D1
CREATE TABLE products (
  id TEXT PRIMARY KEY NOT NULL,
  public_id TEXT,
  name TEXT NOT NULL,
  status TEXT NOT NULL DEFAULT 'draft',
  archived INTEGER NOT NULL DEFAULT 0,
  metadata TEXT,
  legacy_notes TEXT,
  created_at DATETIME NOT NULL,
  updated_at DATETIME NOT NULL
);
CREATE TABLE billing_accounts (
  id TEXT PRIMARY KEY NOT NULL,
  email TEXT NOT NULL
);
CREATE VIEW product_counts AS
  SELECT status, COUNT(*) AS total FROM products GROUP BY status;
```

```sql Postgres
CREATE TABLE products (
  id UUID PRIMARY KEY,
  public_id TEXT,
  name TEXT NOT NULL,
  status TEXT NOT NULL DEFAULT 'draft',
  archived INTEGER NOT NULL DEFAULT 0,
  metadata TEXT,
  legacy_notes TEXT,
  created_at TIMESTAMPTZ NOT NULL,
  updated_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE billing_accounts (
  id UUID PRIMARY KEY,
  email TEXT NOT NULL
);
CREATE VIEW product_counts AS
  SELECT status, COUNT(*)::integer AS total FROM products GROUP BY status;
```

## Defining Models

Define each Model by extending `ApplicationRecord`, as `Account` does:

- **The class name names the table,** so `Product` reads and writes `products`. The table’s attributes, primary key, and types come from `src/db/schema.ts`.
- **[`active-record schema`](/command-line#active-record-schema) writes that file** from your migrations and your Models. Run it after you add a Model or a migration. [`active-record g model`](/generators) runs it for you.
- **The first time it runs, it writes `src/models/application-record.ts`.** It’s an ordinary class, and yours to edit. The schema it holds gives each Model its attributes and the binding its queries use. Methods, callbacks, and scopes you write on it are every Model’s; see [Shared behavior](/shared-behavior). It has no table of its own, so you can’t query it.
- **A subclass shares its parent’s table,** as `FeaturedProduct` does, and inherits a copy of its parent’s attributes, validations, callbacks, scopes, and associations. Declaring more on the child never changes the parent. Single-table inheritance isn’t supported.
- **You can still set `static primaryKey`,** as long as it names an attribute.

## Overriding attributes

Override an attribute in `static attributes` when a column holds something its type doesn’t say, as `Product` does with a boolean in a plain `INTEGER`. Write the object `as const`, so TypeScript keeps each type name. An override is one of these:

| Override                                  | Does                                                                                                           |
| ----------------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `"boolean"` (a type name)                 | Reads and writes the attribute as that type                                                                    |
| `money` (a [custom type](/custom-types)) | Reads and writes the attribute as that type                                                                    |
| `{ type?, null?, default?, generateId? }` | Replaces those parts of the generated attribute; `null: false` makes it non-null in TypeScript                 |
| `{ enum, prefix?, suffix?, … }`           | Makes the attribute an [enum](/enums), of its column’s type                                                   |
| `{ enum: true }`, `{ enum: false }`       | Turns on the methods of an [enum read from the database](/enums#reading-enums-from-the-database), or drops it |
| `false`                                   | Ignores the column: it’s never typed, read, or written, and queries name their columns instead of `*`          |

- **Changing a `type`** drops the generated default or `generateId`, so the column’s own default applies unless you give one. `archived` gives one, so a new product reads `false` before it’s saved.
- **A `default` and `generateId`** replace each other, so an attribute has one or the other. `generateId` is only for strings.
- **A `default`** isn’t type-checked yet ([#74](https://github.com/forestfuture/active-record/issues/74)). One that returns a value the type can’t cast throws `TypeError` when a record is built.
- **Ignoring a `NOT NULL` column** without a default makes inserts fail, so give it a default in a migration first.
- **An override of an attribute the table doesn’t have** throws `InvalidModel`, and `active-record schema` reports it. So does an override that changes a column or ignores the primary key.

## Adding virtual attributes

Add `virtual: true` for a value a form sends but the table doesn’t keep, as `Account` does with `termsOfService`:

```ts
import { Account } from "./models/account";

const form = { email: "jane@example.com", termsOfService: "1" };
const permitted = Account.permit(form, "email", "termsOfService");
const account = Account.build(permitted);
console.log(account.termsOfService); // true, cast from the form's "1"
await account.save(); // inserts the email alone
```

- **It’s typed and cast** like a column’s attribute. `permit` takes it, and its changes are tracked.
- **It’s never saved.** An insert or an update leaves it out. A save that changes only virtual attributes sets `updatedAt` alone, or writes nothing on a table without timestamps.
- **A loaded record starts it at its default,** or `null`, and so does `reload`.
- **A query can’t name it,** since there’s no column to match. `where`, `order`, `select`, `pluck`, `insert`, and `updateAll` throw `UnknownAttribute`.
- **It’s in `toJSON()`,** unless a [`confirmation`](/validations#confirming-a-value) rule reads it. A record keeps it after a create, so list a secret one in [`hiddenAttributes`](/serialization), or `Response.json(user)` sends it back. For a password, declare a [secure password](/passwords-and-tokens) instead, which `toJSON()` leaves out.

:::note
A virtual attribute named for one of the table’s columns throws `InvalidModel`, and so does `virtual` with `column` or `enum`. With `null: false`, give it a `default`. A Model declared with `define` takes `virtual: true` in the same way.
:::

## Normalizing attributes

Declare a normalization in `static {}` to change each value assigned to an attribute into one form, as `Account` does with `email`:

```ts
import { Account } from "./models/account";

const account = await Account.create({ email: " Jane@Example.COM " });
console.log(account.email); // "jane@example.com"

const found = await Account.findBy({ email: "JANE@example.com" }); // the same account
console.log(Account.normalizeValueFor("email", " Sam@Example.com")); // "sam@example.com"
```

- **It runs whenever a value is assigned.** That covers the setter, `build`, `create`, `update`, a default, and bulk writes such as `insert`, `upsert`, and `updateAll`. Several normalizations of one attribute run in order, a parent class’s first.
- **Queries normalize their values too.** `where`, `findBy`, `find`, lists, comparisons, and `column()` values in an `sql` fragment match what was stored. Plain values in an `sql` fragment are left as they are, and `where({ email: null })` still matches `NULL`.
- **`Account.normalizeValueFor("email", value)`** returns a value as assigning it would keep it.

:::warning[Rows saved before stay as they were]
A record loaded from the database keeps its stored value, and a query for that value no longer finds it, since the query is normalized. The same goes for a default scope’s conditions. Normalize each old row, and save it:

```ts
import { Account } from "./models/account";

for await (const account of Account.findEach()) {
  account.normalizeAttribute("email");
  await account.save(); // writes only the accounts whose email changed
}
```

An `UPDATE` in a migration does the same for a large table.
:::

## Aliasing attributes

Add `aliasOf` to give an attribute a second name, as `Product` does with `title` for `name`:

```ts
import { Product } from "./models/product";

const lamp = await Product.create({ title: "Lamp" }); // writes name
console.log(lamp.name); // "Lamp"
const titles = await Product.where({ title: "Lamp" }).pluck("title");
console.log(titles); // ["Lamp"]
lamp.title = "Desk lamp";
console.log(lamp.changes()); // { name: ["Lamp", "Desk lamp"] }
```

- **It reads and writes the attribute it names,** typed as that attribute.
- **Queries and writes take either name:** `where`, `order`, `pluck`, `select`, `group`, the calculations, `build`, `create`, `permit`, `insert`, `upsert`, and `updateAll`.
- **The record holds the value once,** under the attribute’s name. `attributes()`, `toJSON()`, and `changes()` list `name`, and so does a record `select("title")` loads. `attributeWas("title")` and the other methods that take a name read it through the alias.
- **A row that gives both `title` and `name`** throws `TypeError`, since they’re one column.
- **`validates("title", …)` reads through the alias,** and its errors go under `title`.

:::note
An alias of a name that isn’t an attribute throws `InvalidModel`, and so does one named for an attribute, an alias of another alias, or `aliasOf` with any other key. Settings that name an attribute, such as an association’s `foreignKey` or `hiddenAttributes`, take its own name. `filterAttributes` matches an alias too, so naming either one filters the attribute’s values. A Model declared with `define` takes `aliasOf` in the same way.
:::

> **Compared with Rails**
>
> Rails declares an alias with `alias_attribute :title, :name`. Here it goes with the attributes, so it’s typed from the same place. Rails’ `select(:title)` loads the column as `title`; here it loads it as `name`, which `title` reads. Rails follows an alias of an alias; here, name the attribute.

## Narrowing types

Declare an attribute in the class to give it a narrower type than its column’s, as `Product` does with `status`:

- `product.status` is typed `"draft" | "published"`, when you read it and when you assign it.
- `where` and `build` still take any string, and nothing checks the value read from the database. To have the values checked, and get a method for each, declare an [enum](/enums) instead.

## Declaring attributes yourself

Declare the attributes with `define` for a view, or a table your migrations don’t make, as `ProductCount` does:

```ts
import { ProductCount } from "./models/product-count";

const counts = await ProductCount.order({ status: "asc" }).toArray();
// [ProductCount { status: "draft", total: 1 }, ProductCount { status: "published", total: 2 }]
```

- TypeScript infers the record’s properties from the object.
- An attribute is a type name, or `{ type, column?, null?, default? }`.
- Calling `define` on `ApplicationRecord` shares your base class’s behavior and binding.

## Naming Models

A Model’s name is its class name, read with `modelName`:

```ts
import { Account } from "./models/account";
import { FeaturedProduct } from "./models/featured-product";

console.log(FeaturedProduct.modelName); // "FeaturedProduct"
const published = await FeaturedProduct.where({ status: "published" }).toArray(); // from products
const account = await Account.create({ email: "jane@example.com" }); // into billing_accounts
```

- The [generated schema](/schema) lists the Model by its name, and its table name, its foreign keys, and its error messages are made from it.
- If your bundler renames classes, set `static override modelName = "BlogPost"`, so the Model keeps its name once bundled. Without it, a bundler that renames `User` to `e` makes the first query throw `InvalidModel`, because no Model named `e` is in the generated schema. Wrangler keeps class names by default, even when minifying.
- A subclass inherits a `modelName` its parent sets. Otherwise, each class has its own: `FeaturedProduct.modelName` is `"FeaturedProduct"`, though it shares `Product`’s table.

## Naming tables

A Model takes its table name from its name, snake_case and pluralized, unless it sets `static table`, as `Account` does:

| Class      | Table        |
| ---------- | ------------ |
| `User`     | `users`      |
| `BlogPost` | `blog_posts` |
| `Category` | `categories` |
| `Person`   | `people`     |
| `Sheep`    | `sheep`      |

A class with no name to take one from must set `static table`.

:::note
Pluralization follows English rules, quirks included: `Human` becomes `humen` and `Leaf` becomes `leafs`. There’s no way to add your own rules, so set `table` instead.
:::

## Mapping columns

Attributes are camelCase, and map to snake_case columns:

| Attribute           | Column                |
| ------------------- | --------------------- |
| `createdAt`         | `created_at`          |
| `externalAccountId` | `external_account_id` |
| `htmlURL`           | `html_url`            |
| `userID`            | `user_id`             |
| `sha256Hash`        | `sha256_hash`         |

To map an attribute to a column with another name, give it `{ column: "..." }`. Conditions, ordering, and association keys always name attributes; only [SQL fragments](/conditions#writing-sql-fragments) name columns.

## Building records

Build a record without touching the database with `build`:

```ts
import { Product } from "./models/product";

const lamp = Product.build({ name: "Lamp" });
console.log(lamp.id); // generated already, before saving: "3b241101-…"
console.log(lamp.status); // "draft", the column's default
console.log(lamp.archived); // false, read as a boolean
console.log(lamp.createdAt); // null until it's saved

lamp.assign({ status: "published", metadata: { color: "red" } });
await lamp.save(); // sets createdAt and updatedAt
```

- **Defaults** and [generated ids](#generating-ids) run at `build()`, so a key generated in code exists before the record is saved. That lets records that point at each other be saved together, in one atomic batch.
- **Unassigned attributes** read as `null`, and aren’t written on insert, so the column’s database default applies. After the insert, the record loads what the database stored.
- **Unknown attributes** throw `UnknownAttribute`, and `undefined` throws `TypeError`. Use `null` to store NULL.
- `assign(attrs)` sets several attributes without saving. `update(attrs)` assigns, then saves.

:::note
A record keeps the database it was built or loaded through, for its later saves and association loads. A record made with `new Product()` has none, so build records with `Product.build(…)`.
:::

## Permitting fields

Keep only the attributes you name from untrusted input with `permit`, whose result goes straight into `build`, `create`, or `update`:

```ts
import { Product } from "./models/product";

export async function createProduct(request: Request) {
  const permitted = Product.permit(await request.json(), "name", "metadata");
  return Product.create(permitted); // any other key in the body is dropped
}
```

It casts each value as assigning would, and reads three kinds of input:

| Input             | Read                                                             |
| ----------------- | ---------------------------------------------------------------- |
| a plain object    | its own keys only, so `__proto__` and inherited keys never count |
| `FormData`        | each field; a repeated key takes its last value                  |
| `URLSearchParams` | each parameter; a repeated key takes its last value              |

- **Keys you don’t name** are dropped. A named attribute the input doesn’t have is left out, and a `null` is kept.
- **A name that isn’t an attribute** is a compile error, and throws `UnknownAttribute`.
- **`TypeError`** is thrown for a value that can’t be cast, a file from a form (read a file’s bytes for a [`binary` attribute](/attribute-types#storing-bytes)), and any other input: an array, a `Map`, `Headers`, a class instance, `null`, or a string.

[Untrusted input](/untrusted-input) shows `permit` in a Worker.

## Generating ids

A `TEXT` or `UUID` primary key gets its value from the Model’s `generateId` when you don’t give one. By default, that’s a UUID:

- To use another kind of id across your app, override it on your app’s base class: `static override generateId = () => uuidv7()`. It gets the attribute’s name, so it can prefix ids: `` `${attribute}_${uuidv7()}` ``.
- To generate another string attribute the same way, turn it on with an override, as `Product` does with `publicId: { generateId: true }`.
- For one attribute with its own format, use a `default`: ``shareToken: { default: () => `share_${uuidv7()}` }``. A value made from other attributes, such as a slug, belongs in a [callback](/callbacks), since `generateId` never sees the record.

## Using timestamps

Declare `createdAt` and `updatedAt` as `datetime` attributes, and they’re managed for you:

- Both are set when a record is created, and `updatedAt` whenever a save changes something.
- A save with nothing to change leaves `updatedAt` alone, and a timestamp you assign yourself is kept.

## Checking declarations

A Model’s declaration is checked the first time it’s used, by its first query or `db.model(X)`, and it throws `InvalidModel` for:

- A Model `active-record schema` hasn’t seen, or whose table has changed since. Run it again.
- No table name: an empty `table`, or a class with no name to infer one from.
- A `modelName` that isn’t a string.
- An override of an attribute the table doesn’t have.
- A `primaryKey` that isn’t an attribute.
- An attribute named like a record method, such as `save` or `attributes`.
- A class field that hides an attribute, such as `email!: string` in the class body.
- A normalization of a name that isn’t one of the Model’s attributes.

After that, a Model’s declarations are fixed, so request code can’t change them.

> **Compared with Rails**
>
> `modelName` is a string, where Rails’ `model_name` is an object.
>
> `normalizes` takes one attribute, where Rails’ takes several. Its result is cast to the attribute’s type again, which Rails doesn’t do. Rails also normalizes an association’s link to its owner. Here the link is the owner’s key as it is, so normalizing a foreign key can’t bring another owner’s records into `author.posts()`.

> **Beyond Rails**
>
> Rails has no `generateId`. Its UUID keys come from the database (`gen_random_uuid()` in PostgreSQL), which D1 can’t do for a key a batch needs before the row is written. See [Primary keys](/coming-from-rails#primary-keys).
