---
title: Shared behavior
description: "Write methods, callbacks, and scopes once, on your app’s base class."
seo:
  description: "Share methods, callbacks, and scopes across every Active Record Model by writing them once on your app’s ApplicationRecord base class."
---

## At a glance

| To                                      | Write, on `ApplicationRecord`                            |
| --------------------------------------- | -------------------------------------------------------- |
| give every record a method              | `label() { … }`                                          |
| run a callback for every Model          | `this.beforeSave(…)`, in `static {}`                     |
| give every Model a scope                | ``static newest = this.scope((q) => q.order(sql`…`))``   |
| share behavior between only some Models | an `abstract` class between them and `ApplicationRecord` |

## The Models

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

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

// What's written on ApplicationRecord, every Model has.
export abstract class ApplicationRecord extends Model {
  static override schema = schema;

  static newest = this.scope((q) => q.order(sql`created_at DESC`));

  label() {
    return `${this.constructor.name} ${JSON.stringify(this.attributes())}`;
  }

  static {
    this.beforeSave((record) => {
      console.log(`Saving ${record.constructor.name}`); // before each Model's own callbacks
    });
  }
}
```

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

export class Product extends ApplicationRecord {}
```

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

// Shared by only the Models that extend it. It has no table of its own.
export abstract class Auditable extends ApplicationRecord {
  static override abstract = true;

  static {
    this.afterSave((record) => {
      console.log(`Saved ${record.constructor.name}`);
    });
  }
}
```

```ts invoice.ts
import { Auditable } from "./auditable";

export class Invoice extends Auditable {}
```

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

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

/** invoices — last changed by 0001_create_tables.sql */
export const invoices = {
  id: { type: "string", null: false, generateId: true },
  totalCents: { type: "integer", null: false },
  createdAt: { type: "datetime", null: false },
} as const;

/** products — last changed by 0001_create_tables.sql */
export const products = {
  id: { type: "string", null: false, generateId: true },
  name: { type: "string", null: false },
  createdAt: { 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: {
    invoices: { attributes: invoices, primaryKey: "id" },
    products: { attributes: products, primaryKey: "id" },
  },
  models: { Invoice: "invoices", Product: "products" },
});

declare module "../models/invoice" {
  interface Invoice extends TableAttributes<typeof invoices, (typeof Invoice)["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,
  name TEXT NOT NULL,
  created_at DATETIME NOT NULL
);
CREATE TABLE invoices (
  id TEXT PRIMARY KEY NOT NULL,
  total_cents INTEGER NOT NULL,
  created_at DATETIME NOT NULL
);
```

```sql Postgres
CREATE TABLE products (
  id UUID PRIMARY KEY,
  name TEXT NOT NULL,
  created_at TIMESTAMPTZ NOT NULL
);
CREATE TABLE invoices (
  id UUID PRIMARY KEY,
  total_cents INTEGER NOT NULL,
  created_at TIMESTAMPTZ NOT NULL
);
```

## Sharing methods, callbacks, and scopes

Write them on `ApplicationRecord`, in `src/models/application-record.ts`, and every Model has them, as `Product` does:

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

const lamp = await Product.create({ name: "Lamp" }); // logs "Saving Product"
console.log(lamp.label()); // Product {"id":"…","name":"Lamp","createdAt":"…"}
const newest = await Product.newest().first(); // the shared scope, on products
```

Each is shared like this:

| On `ApplicationRecord`                   | Every Model                                            |
| ---------------------------------------- | ------------------------------------------------------ |
| A method, such as `label()`              | has it, on every record                                |
| A static method                          | has it, on the Model                                   |
| A callback, in `static {}`               | runs it, before the Model’s own callbacks of that kind |
| A scope, `static newest = this.scope(…)` | has it, as `Product.newest()` and on its Relations     |
| `static override onQuery`                | logs its queries (see [Logging](/logging))            |

A Model can replace a shared method or scope by declaring one of the same name.

:::note
`active-record schema` writes `application-record.ts` with commented-out examples to start from.
:::

## Writing for every table

Inside `ApplicationRecord`, `this` is a record of any Model. It has every record method, such as `save()` and `attributes()`, but no attributes, since those differ from table to table:

- Read attributes through `this.attributes()`, as `label()` does.
- Write shared scopes with `sql` fragments, as `newest` does, since they run on each Model’s own table.
- Validations name attributes, so they belong on each Model. Put shared checks in a callback instead.

`ApplicationRecord` has no table of its own, so `db.model(ApplicationRecord)` throws `InvalidModel`. Once a Model has been used, `ApplicationRecord` is sealed with it, so request code can’t add callbacks to every Model.

## Sharing behavior between some Models

To share behavior between only some Models, put it on a class between them and `ApplicationRecord`, marked `abstract`, as `Auditable` is:

```ts
import { Invoice } from "./models/invoice";

await Invoice.create({ totalCents: 1200 }); // logs "Saving Invoice", then "Saved Invoice"
```

`Auditable` has no table. Each class that extends it has its own, so `Invoice` reads and writes `invoices`.

## Sharing across databases

Each database has its own base class, such as `DbRecord` and `LogsRecord`, holding its own schema. To share behavior across all of them, write it on one abstract class extending `Model`, and extend that class in each base class’s file:

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

export abstract class AppRecord extends Model {
  label() {
    return `${this.constructor.name} ${JSON.stringify(this.attributes())}`;
  }
}

export abstract class LogsRecord extends AppRecord {
  static override schema = schema;
}
```

See [Multiple databases](/several-databases).
