---
title: Read-only records
description: "Load records that can’t be saved, and attributes that are set only on create."
seo:
  description: "Read-only records and attributes in Active Record: readonly() Relations, markReadonly(), ReadonlyRecord for a refused save or destroy, and readonly attributes set only on create."
---

## At a glance

| To                                      | Write                                                      |
| --------------------------------------- | ---------------------------------------------------------- |
| load records that can’t be saved        | `Article.readonly().toArray()`                             |
| make one record read-only               | `article.markReadonly()`                                   |
| ask whether a record is read-only       | `article.isReadonly()`                                     |
| catch a refused write                   | `catch (error) { if (error instanceof ReadonlyRecord) … }` |
| set an attribute only when it’s created | `slug: { readonly: true }` in the Model’s `attributes`     |

## The Model

The examples use this Model, whose attributes come from its table through the schema `active-record schema` generates:

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

export class Article extends ApplicationRecord {
  static override attributes = {
    slug: { readonly: true }, // set when the article is created, never changed after
  } as const;
}
```

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

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

/** articles — last changed by 0001_create_articles.sql */
export const articles = {
  id: { type: "string", null: false, generateId: true },
  title: { type: "string", null: false },
  slug: { type: "string", null: false },
  body: "string",
  updatedAt: "datetime",
} 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: {
    articles: { attributes: articles, primaryKey: "id" },
  },
  models: { Article: "articles" },
});

declare module "../models/article" {
  interface Article extends TableAttributes<typeof articles, (typeof Article)["attributes"]> {}
}
```

```sql D1
CREATE TABLE articles (
  id TEXT PRIMARY KEY NOT NULL,
  title TEXT NOT NULL,
  slug TEXT NOT NULL UNIQUE,
  body TEXT,
  updated_at DATETIME
);
```

```sql Postgres
CREATE TABLE articles (
  id UUID PRIMARY KEY,
  title TEXT NOT NULL,
  slug TEXT NOT NULL UNIQUE,
  body TEXT,
  updated_at TIMESTAMPTZ
);
```

## Loading read-only records

Call `readonly()` on a query, and the records it loads can’t be saved:

```ts
import { Article } from "./models/article";

const articles = await Article.readonly().order({ title: "asc" }).toArray();
console.log(articles[0]?.isReadonly()); // true

const article = await Article.readonly().findByOrThrow({ slug: "hello" });
article.title = "Hello, world";
await article.save(); // throws ReadonlyRecord, and sends nothing
```

- Every way a query loads records marks them: `toArray()`, `find`, `findBy`, `first`, `sole`, `findEach`, and the rest.
- Chaining keeps it, and so does `merge`. A scope, a default scope, or an association’s `scope` can call it too. `readonly(false)` undoes it.
- The records `includes` preloads aren’t read-only, unless an association’s `scope` calls `readonly()`. Records the query builds or creates aren’t read-only either.

## Marking one record

`markReadonly()` makes a record you already have read-only:

```ts
import { Article } from "./models/article";

const article = await Article.findByOrThrow({ slug: "hello" });
article.markReadonly();

console.log(article.isReadonly()); // true
await article.destroy(); // throws ReadonlyRecord, and the article stays
```

A read-only record can still change in memory, and `reload()` still reads its row. It stays read-only.

## Refusing writes

Saving, updating, destroying, or touching a read-only record throws `ReadonlyRecord`, and so do `updateColumns`, `updateColumn`, `incrementColumn`, `decrementColumn`, and `toggleColumn`:

```ts
import { ReadonlyRecord } from "@forestfuture/active-record";
import { Article } from "./models/article";

const article = await Article.findByOrThrow({ slug: "hello" });
article.markReadonly();
try {
  await article.touch();
} catch (error) {
  if (!(error instanceof ReadonlyRecord)) throw error;
  console.log(error.action); // "touch"
}
```

- It throws before validation or any callback runs, and sends nothing.
- `save()` throws too, rather than returning `false`.
- The error’s `record` is the refused record, and its `action` names what was refused: `"save"`, `"destroy"`, `"touch"`, or the column method.
- A write that would reach a read-only record through another throws too, and writes nothing. Saving an owner that [autosaves](/autosaving) a changed read-only record, a [batch](/batches) holding one, and a has-many’s `push` throw before any callback runs. So does a write that would [touch](/touching) a loaded read-only record.
- Some records are only loaded partway through a write: the record a has-one’s new record replaces, and a `dependent: "destroy"` association’s records. A read-only one throws once it’s loaded, after the owner’s before-callbacks, and nothing is written.

## Writing past it

Bulk writes don’t load records, so `readonly()` doesn’t stop them:

```ts
import { Article } from "./models/article";

const updated = await Article.readonly().where({ slug: "hello" }).updateAll({ body: "" });
console.log(updated); // 1: a bulk write doesn't load records, so it isn't refused
```

`updateAll`, `deleteAll`, `insert`, and `upsert` all write as usual. So do the removals that work like them: `dependent: "delete"`, a has-one replacement whose `dependent` is `"delete"`, and a has-many’s `delete()` and `clear()`.

## Declaring read-only attributes

Give an attribute `readonly: true`, and it’s written when its record is created, then never changed by it:

```ts
import { Article } from "./models/article";

const article = await Article.create({ title: "Getting started", slug: "getting-started" });
console.log(article.slug); // "getting-started"

article.slug = "first-steps"; // throws ReadonlyAttribute: it's set when it's created
```

- Assigning a saved record a new value throws `ReadonlyAttribute` straight away, whether you assign it, `update()` it, or write it with `updateColumns`. The error’s `attribute` names it.
- Pointing a belongs-to at another record throws `ReadonlyAttribute` when its read-only foreign key would change. So does saving a record whose read-only foreign key a new record would fill once it’s inserted.
- Changing a JSON value or a `Date` in place makes the save throw before anything runs. `touch()` refuses a read-only datetime the same way.
- A new record can change it until it’s saved.
- A [counter cache](/counter-caches) still counts a read-only column, so a save can’t overwrite the count. `Model.updateCounters` and `touchAll` write rows without loading them, as `updateAll` does, so they write a read-only column too.
- An `upsert` leaves the value of a row it updates alone. `updateAll` still writes it.
- A virtual attribute, a secure password, and a secure token can’t be read-only. Neither can `updatedAt` or `lockVersion`, which every save writes.

## Posting it back from a form

Assigning the value an attribute already holds isn’t a change, so a form that sends every field back still saves:

```ts
import { ReadonlyAttribute } from "@forestfuture/active-record";
import { Article } from "./models/article";

export async function updateArticle(request: Request): Promise<Response> {
  const id = new URL(request.url).searchParams.get("id") ?? "";
  const article = await Article.find(id);
  const form = await request.formData();
  const changes = Article.permit(form, "title", "slug");
  try {
    // A form that posts the slug back unchanged saves; one that changes it doesn't
    await article.updateOrThrow(changes);
  } catch (error) {
    if (!(error instanceof ReadonlyAttribute)) throw error;
    return new Response(`An article's ${error.attribute} can't be changed.`, { status: 422 });
  }
  return new Response("Saved");
}
```

The value is compared after it’s cast and normalized, so `" Hello "` matches `"hello"` when a [normalization](/models#normalizing-attributes) trims and lowercases it.

> **Compared with Rails**
>
> Rails names the error `ActiveRecord::ReadOnlyRecord`, and its record method is `readonly!`. Here it’s `markReadonly()`.
>
> Rails runs a read-only record’s own save and destroy callbacks, `dependent: :destroy` included, before it raises. Here they don’t run.
>
> With Rails 7.1’s defaults, `attr_readonly` raises `ActiveRecord::ReadonlyAttributeError` on any assignment to a saved record. Here assigning the value it holds is allowed.
