---
title: Change tracking
description: "A record knows what’s changed since it was loaded or last saved."
seo:
  description: "Track Active Record changes: changed, attributeWas, and isAttributeChanged before a save, savedChangeTo after it, and restoreAttributes to undo unsaved changes."
---

## At a glance

| To                                          | Write                                                                     |
| ------------------------------------------- | ------------------------------------------------------------------------- |
| check for unsaved changes                   | `isChanged()`, `changed()`, `changes()`                                   |
| read an attribute’s value before the change | `attributeWas("email")`                                                   |
| check one attribute’s change                | `isAttributeChanged("email", { from: "…" })`, `willSaveChangeTo("email")` |
| read what the last save changed             | `savedChanges()`, `savedChangeTo("email")`, `hasSavedChangeTo("email")`   |
| undo unsaved changes                        | `restoreAttributes()`, or `restoreAttributes(["email"])`                  |

## The Model

The examples use this Model, whose attributes come from its table through the schema `active-record schema` generates. Its `afterSave` callback reads what each save changed:

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

export class User extends ApplicationRecord {
  static {
    // After a save, the record is clean: read what the save changed.
    this.afterSave((user) => {
      const change = user.savedChangeTo("email");
      if (change) console.log(`Email changed from ${change[0]} to ${change[1]}`);
    });
  }
}
```

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

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

/** users — last changed by 0001_create_users.sql */
export const users = {
  id: { type: "string", null: false, generateId: true },
  email: { type: "string", null: false },
  role: "string",
  isActive: "boolean",
  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: {
    users: { attributes: users, primaryKey: "id" },
  },
  models: { User: "users" },
});

declare module "../models/user" {
  interface User extends TableAttributes<typeof users, (typeof User)["attributes"]> {}
}
```

```sql D1
CREATE TABLE users (
  id TEXT PRIMARY KEY NOT NULL,
  email TEXT NOT NULL,
  role TEXT,
  is_active BOOLEAN,
  created_at DATETIME NOT NULL,
  updated_at DATETIME NOT NULL
);
```

```sql Postgres
CREATE TABLE users (
  id UUID PRIMARY KEY,
  email TEXT NOT NULL,
  role TEXT,
  is_active BOOLEAN,
  created_at TIMESTAMPTZ NOT NULL,
  updated_at TIMESTAMPTZ NOT NULL
);
```

## Reading changes

Read a record’s changes before it’s saved, and what the save changed after:

```ts
import { User } from "./models/user";

const user = await User.findByOrThrow({ email: "jane@example.com" });
user.email = "jane@work.example";

console.log(user.changed()); // ["email"]
console.log(user.attributeWas("email")); // "jane@example.com"
console.log(user.isAttributeChanged("email", { from: "jane@example.com" })); // true

await user.save(); // logs "Email changed from jane@example.com to jane@work.example"
console.log(user.isChanged()); // false
```

- `isChanged()`, `changed()`, `changedAttributes()`, and `changes()` describe the unsaved changes. A new record’s changes run from its defaults, so a default it keeps isn’t a change.
- `attributeWas`, `isAttributeChanged`, and `willSaveChangeTo` look at one attribute’s unsaved change. Use them in before-callbacks.
- `savedChanges()`, `savedChangeTo`, `hasSavedChangeTo`, and `attributeBeforeLastSave` look at the last save. Use them in after-callbacks, where the record is already clean, as `User` does.
- An update writes only the attributes that changed, and a save with nothing changed sends nothing.

:::note
Changes are found by comparing stored values, so editing a `json` value, a `Date`, or a `binary` attribute’s bytes in place counts as a change.
:::

## Undoing changes

Undo unsaved changes with `restoreAttributes`, to every attribute or the ones you name:

```ts
import { User } from "./models/user";

const user = await User.findByOrThrow({ email: "jane@example.com" });
user.assign({ email: "typo@example", role: "owner" });
user.restoreAttributes(["email"]); // back to "jane@example.com"; role stays changed
```

