---
title: Enums
description: "Give an attribute a fixed set of names, with a predicate, a setter, and scopes for each."
seo:
  description: "Active Record enums: declare an attribute’s names as a list or with stored values, use their predicates, setters, and scopes, and read enums from CHECKs."
---

## At a glance

| To                                  | Write                                                         |
| ----------------------------------- | ------------------------------------------------------------- |
| store each name as itself           | `status: { enum: ["open", "in_progress", "closed"] }`         |
| store each name as a value          | `priority: { enum: { low: 0, normal: 1, high: 2 } }`          |
| check a record’s name               | `ticket.isOpen()`                                             |
| set it and save                     | `ticket.saveAsClosed()`, `ticket.saveAsClosedOrThrow()`       |
| find records by name                | `Ticket.open()`, `Ticket.notClosed()`, `where({ status: … })` |
| read names with their stored values | `Ticket.enumValues("priority")`                               |
| keep two enums’ methods apart       | `prefix: true`, `suffix: true`                                |
| report an unknown name as invalid   | `validate: true`                                              |
| use the names a `CHECK` lists       | `state: { enum: true }`                                       |

## The Models

The examples use these Models. Their attributes come from their tables through the schema `active-record schema` generates, and each declares its enum in an override:

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

export class Ticket extends ApplicationRecord {
  static override attributes = {
    status: { enum: ["open", "in_progress", "closed"] }, // stored as the names
    priority: { enum: { low: 0, normal: 1, high: 2 } }, // stored as 0, 1, and 2
  } as const;
}
```

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

export class Conversation extends ApplicationRecord {
  static override attributes = {
    status: { enum: ["active", "archived"], prefix: true }, // isStatusActive()
    comments: { enum: ["active", "closed"], suffix: true }, // Conversation.activeComments()
  } as const;
}
```

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

export class Survey extends ApplicationRecord {
  static override attributes = {
    answer: { enum: ["yes", "no"], validate: true }, // an inclusion error, not a TypeError
  } as const;
}
```

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

export class Task extends ApplicationRecord {
  static override attributes = { state: { enum: true } } as const; // the CHECK's names, with methods
}
```

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

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

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

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

/** tasks — last changed by 0001_create_tables.sql */
export const tasks = {
  id: { type: "string", null: false, generateId: true },
  state: { type: "string", null: false, enum: ["open", "done"], scopes: false, instanceMethods: false },
} as const;

/** tickets — last changed by 0001_create_tables.sql */
export const tickets = {
  id: { type: "string", null: false, generateId: true },
  title: { type: "string", null: false },
  status: "string",
  priority: "integer",
} 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: {
    conversations: { attributes: conversations, primaryKey: "id" },
    surveys: { attributes: surveys, primaryKey: "id" },
    tasks: { attributes: tasks, primaryKey: "id" },
    tickets: { attributes: tickets, primaryKey: "id" },
  },
  models: { Conversation: "conversations", Survey: "surveys", Task: "tasks", Ticket: "tickets" },
  enumScopes: {
    Conversation: ["statusActive", "notStatusActive", "statusArchived", "notStatusArchived", "activeComments", "notActiveComments", "closedComments", "notClosedComments"],
    Survey: ["yes", "notYes", "no", "notNo"],
    Task: ["open", "notOpen", "done", "notDone"],
    Ticket: ["open", "notOpen", "inProgress", "notInProgress", "closed", "notClosed", "low", "notLow", "normal", "notNormal", "high", "notHigh"],
  },
});

declare module "../models/conversation" {
  interface Conversation
    extends TableAttributes<typeof conversations, (typeof Conversation)["attributes"]> {}
  namespace Conversation {
    export const statusActive: ScopeStatic<[]>;
    export const notStatusActive: ScopeStatic<[]>;
    export const statusArchived: ScopeStatic<[]>;
    export const notStatusArchived: ScopeStatic<[]>;
    export const activeComments: ScopeStatic<[]>;
    export const notActiveComments: ScopeStatic<[]>;
    export const closedComments: ScopeStatic<[]>;
    export const notClosedComments: ScopeStatic<[]>;
  }
}

declare module "../models/survey" {
  interface Survey extends TableAttributes<typeof surveys, (typeof Survey)["attributes"]> {}
  namespace Survey {
    export const yes: ScopeStatic<[]>;
    export const notYes: ScopeStatic<[]>;
    export const no: ScopeStatic<[]>;
    export const notNo: ScopeStatic<[]>;
  }
}

declare module "../models/task" {
  interface Task extends TableAttributes<typeof tasks, (typeof Task)["attributes"]> {}
  namespace Task {
    export const open: ScopeStatic<[]>;
    export const notOpen: ScopeStatic<[]>;
    export const done: ScopeStatic<[]>;
    export const notDone: ScopeStatic<[]>;
  }
}

declare module "../models/ticket" {
  interface Ticket extends TableAttributes<typeof tickets, (typeof Ticket)["attributes"]> {}
  namespace Ticket {
    export const open: ScopeStatic<[]>;
    export const notOpen: ScopeStatic<[]>;
    export const inProgress: ScopeStatic<[]>;
    export const notInProgress: ScopeStatic<[]>;
    export const closed: ScopeStatic<[]>;
    export const notClosed: ScopeStatic<[]>;
    export const low: ScopeStatic<[]>;
    export const notLow: ScopeStatic<[]>;
    export const normal: ScopeStatic<[]>;
    export const notNormal: ScopeStatic<[]>;
    export const high: ScopeStatic<[]>;
    export const notHigh: ScopeStatic<[]>;
  }
}
```

```sql D1
CREATE TABLE tickets (
  id TEXT PRIMARY KEY NOT NULL,
  title TEXT NOT NULL,
  status TEXT,
  priority INTEGER
);
CREATE TABLE conversations (
  id TEXT PRIMARY KEY NOT NULL,
  status TEXT,
  comments TEXT
);
CREATE TABLE surveys (
  id TEXT PRIMARY KEY NOT NULL,
  answer TEXT
);
CREATE TABLE tasks (
  id TEXT PRIMARY KEY NOT NULL,
  state TEXT NOT NULL CHECK (state IN ('open', 'done'))
);
```

```sql Postgres
CREATE TABLE tickets (
  id UUID PRIMARY KEY,
  title TEXT NOT NULL,
  status TEXT,
  priority INTEGER
);
CREATE TABLE conversations (
  id UUID PRIMARY KEY,
  status TEXT,
  comments TEXT
);
CREATE TABLE surveys (
  id UUID PRIMARY KEY,
  answer TEXT
);
CREATE TABLE tasks (
  id UUID PRIMARY KEY,
  state TEXT NOT NULL CHECK (state IN ('open', 'done'))
);
```

## Declaring enums

Declare an enum with `enum` in an override, as `Ticket` does:

- The attribute’s type is the union of its names: `"open" | "in_progress" | "closed" | null`.
- A list of names stores each name as itself, as text.
- An object stores each name as the value you give it, an integer for an `INTEGER` column or text for a `TEXT` one.

## Using an enum’s methods

Each name gets a predicate and a setter on records, and two scopes on the Model:

```ts
import { Ticket } from "./models/ticket";

const ticket = await Ticket.high().notClosed().first();
if (ticket?.isOpen()) await ticket.saveAsClosed();

const unfinished = await Ticket.where({ status: ["open", "in_progress"] }).count();
```

| Method                                                  | Does                                                                     |
| ------------------------------------------------------- | ------------------------------------------------------------------------ |
| `ticket.isOpen()`                                       | Whether `status` is `"open"`                                             |
| `ticket.saveAsClosed()`, `ticket.saveAsClosedOrThrow()` | Sets `status` to `"closed"` and saves the record, with its other changes |
| `Ticket.open()`, `Ticket.notOpen()`                     | Scopes of the records whose `status` is, or isn’t, `"open"`              |

- A name in snake_case reads in camelCase: `in_progress` gives `isInProgress()` and `Ticket.inProgress()`.
- `saveAsClosed()` returns `false` when the record is invalid, as `save` does, and `saveAsClosedOrThrow()` throws.
- `where`, `whereNot`, `pluck`, and every write take and give names, one or a list.

:::note
Record methods follow your override as soon as you save it. The scopes are typed in the generated schema, so run `active-record schema` (or keep `--watch` running) after you add an enum.
:::

## Reading stored values

Read an enum’s names with their stored values with `enumValues`:

```ts
import { Ticket } from "./models/ticket";

const priorities = Ticket.enumValues("priority"); // { low: 0, normal: 1, high: 2 }
```

## Keeping names apart

Add a `prefix` or a `suffix` when two enums share a name, `true` for the attribute’s name or a word of your own, as `Conversation` does:

```ts
import { Conversation } from "./models/conversation";

const conversation = await Conversation.activeComments().firstOrThrow();
const live = conversation.isStatusActive();
```

- A method name that’s taken, by another enum, an attribute, a record method, or a static, throws `InvalidModel` when the Model is first used, and `active-record schema` reports it.
- So does a name TypeScript can’t declare, such as `in-progress` or `new`. Map a readable name to the stored value instead: `enum: { inProgress: "in-progress" }`.
- To leave an enum’s methods out, declare it with `scopes: false` or `instanceMethods: false`.

## Reading and assigning other values

Assigning a value that isn’t one of an enum’s names, or one of its stored values, throws `TypeError`, and a condition with one matches nothing:

- A stored value that the enum doesn’t list reads as `null`, so rows written by a newer deploy don’t break an older one. This holds even for an attribute declared `null: false`.
- To rename a name without touching stored rows, map the new name to the old value: `enum: { drafted: "draft" }`. Otherwise, migrate the rows in the same deploy.

## Validating names

Declare an enum with `validate: true`, as `Survey` does, to report an unknown value as a validation error instead of throwing:

```ts
import { Survey } from "./models/survey";

const survey = Survey.build(JSON.parse('{ "answer": "maybe" }'));
await survey.save(); // false
console.log(survey.errors.fullMessages()); // ["Answer is not included in the list"]
```

A survey with no answer is invalid too, unless you declare `validate: { allowNull: true }`.

## Reading enums from the database

`active-record schema` writes the names a database restricts a column to into the generated schema, with the enum’s methods off. A Postgres enum type does it, and so does a `CHECK` such as the `tasks` table’s. Turn the methods on with `enum: true`, as `Task` does:

```ts
import { Task } from "./models/task";

const task = await Task.open().firstOrThrow();
await task.saveAsDone(); // task.isDone() is now true
```

- The attribute’s type is `"open" | "done"`, assigning any other value throws `TypeError`, and `enumValues` works as for any enum.
- `enum: true` keeps the database’s names, so a name a later migration adds gets its methods the next time you run `active-record schema`.
- A `scopes: false` or `instanceMethods: false` beside it still leaves those out, and `scopes: true` or `instanceMethods: true` alone turns on one kind. Names that clash only matter once their methods are on, and you fix them as in [Keeping names apart](#keeping-names-apart).
- To keep the column a plain string, override it with `enum: false`. A list of your own, such as `enum: ["open", "done", "archived"]`, replaces the database’s, with its methods on.

:::note
`active-record schema` reads a `CHECK` whose only condition is `column IN (…)` with text values, or `column IS NULL OR column IN (…)`. Any other `CHECK` leaves the column as it was, and a list of numbers stays an `integer`. Postgres stores a one-name `IN ('open')` as `= 'open'`, so it isn’t read there.
:::

> **Compared with Rails**
>
> Rails declares `enum :status, [:open, :closed]` and stores a list by position. Here a list stores the names, so reordering it changes nothing. `published?` is `isPublished()`, `published!` is `saveAsPublished()` or `saveAsPublishedOrThrow()`, `not_published` is `notPublished()`, and `Post.statuses` is `Post.enumValues("status")`. Two names stored as one value are refused.

> **Beyond Rails**
>
> Rails reads no enums from the database: each one is declared in its Model. Here the database gives an enum its names and its type, and the Model still declares its methods, with `enum: true`.
