---
title: Touching
description: "Set a record’s updatedAt whenever a record it’s associated with changes."
seo:
  description: "Touch Active Record associations: set updatedAt on the record a belongsTo or hasOne reaches, name other attributes, and turn touches off with noTouching."
---

## At a glance

| To                                          | Write                                          |
| ------------------------------------------- | ---------------------------------------------- |
| touch an article whenever a comment changes | `belongsTo(Article, { touch: true })`          |
| set another datetime attribute too          | `touch: "lastCommentedAt"`, or a list of names |
| touch a profile whenever its user changes   | `hasOne(Profile, { touch: true })`             |
| touch a record yourself                     | `comment.touch()`                              |
| skip touches during an import               | `Article.noTouching(async () => { … })`        |

## The Models

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

```ts comment.ts
import { belongsTo } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Article } from "./article";

export class Comment extends ApplicationRecord {
  article = belongsTo(Article, { touch: true }); // sets the article's updatedAt
}
```

```ts article.ts
import { belongsTo, hasMany } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Blog } from "./blog";
import { Comment } from "./comment";

export class Article extends ApplicationRecord {
  blog = belongsTo(Blog, { touch: true }); // touching an article touches its blog
  comments = hasMany(Comment);
}
```

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

export class Blog extends ApplicationRecord {}
```

```ts reply.ts
import { belongsTo } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Article } from "./article";

export class Reply extends ApplicationRecord {
  static override table = "comments";

  article = belongsTo(Article, { touch: "lastCommentedAt" }); // and updatedAt
}
```

```ts user.ts
import { hasOne } from "@forestfuture/active-record";
import { ApplicationRecord } from "./application-record";
import { Profile } from "./profile";

export class User extends ApplicationRecord {
  profile = hasOne(Profile, { touch: true }); // sets the profile's updatedAt
}
```

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

export class Profile extends ApplicationRecord {}
```

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

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

/** articles — last changed by 0001_create_tables.sql */
export const articles = {
  id: { type: "string", null: false, generateId: true },
  blogId: { type: "string", null: false },
  title: { type: "string", null: false },
  updatedAt: "datetime",
  lastCommentedAt: "datetime",
} as const;

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

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

/** profiles — last changed by 0001_create_tables.sql */
export const profiles = {
  id: { type: "string", null: false, generateId: true },
  userId: { type: "string", null: false },
  bio: "string",
  updatedAt: "datetime",
} as const;

/** users — last changed by 0001_create_tables.sql */
export const users = {
  id: { type: "string", null: false, generateId: true },
  name: { type: "string", null: false },
  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" },
    blogs: { attributes: blogs, primaryKey: "id" },
    comments: { attributes: comments, primaryKey: "id" },
    profiles: { attributes: profiles, primaryKey: "id" },
    users: { attributes: users, primaryKey: "id" },
  },
  models: {
    Article: "articles",
    Blog: "blogs",
    Comment: "comments",
    Profile: "profiles",
    Reply: "comments",
    User: "users",
  },
});

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

declare module "../models/blog" {
  interface Blog extends TableAttributes<typeof blogs, (typeof Blog)["attributes"]> {}
}

declare module "../models/comment" {
  interface Comment extends TableAttributes<typeof comments, (typeof Comment)["attributes"]> {}
}

declare module "../models/profile" {
  interface Profile extends TableAttributes<typeof profiles, (typeof Profile)["attributes"]> {}
}

declare module "../models/reply" {
  interface Reply extends TableAttributes<typeof comments, (typeof Reply)["attributes"]> {}
}

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

```sql D1
CREATE TABLE blogs (
  id TEXT PRIMARY KEY NOT NULL,
  updated_at DATETIME
);
CREATE TABLE articles (
  id TEXT PRIMARY KEY NOT NULL,
  blog_id TEXT NOT NULL REFERENCES blogs (id),
  title TEXT NOT NULL,
  updated_at DATETIME,
  last_commented_at DATETIME
);
CREATE TABLE comments (
  id TEXT PRIMARY KEY NOT NULL,
  article_id TEXT NOT NULL REFERENCES articles (id),
  body TEXT NOT NULL,
  updated_at DATETIME
);
CREATE TABLE users (
  id TEXT PRIMARY KEY NOT NULL,
  name TEXT NOT NULL,
  updated_at DATETIME
);
CREATE TABLE profiles (
  id TEXT PRIMARY KEY NOT NULL,
  user_id TEXT NOT NULL REFERENCES users (id),
  bio TEXT,
  updated_at DATETIME
);
```

```sql Postgres
CREATE TABLE blogs (
  id UUID PRIMARY KEY,
  updated_at TIMESTAMPTZ
);
CREATE TABLE articles (
  id UUID PRIMARY KEY,
  blog_id UUID NOT NULL REFERENCES blogs (id),
  title TEXT NOT NULL,
  updated_at TIMESTAMPTZ,
  last_commented_at TIMESTAMPTZ
);
CREATE TABLE comments (
  id UUID PRIMARY KEY,
  article_id UUID NOT NULL REFERENCES articles (id),
  body TEXT NOT NULL,
  updated_at TIMESTAMPTZ
);
CREATE TABLE users (
  id UUID PRIMARY KEY,
  name TEXT NOT NULL,
  updated_at TIMESTAMPTZ
);
CREATE TABLE profiles (
  id UUID PRIMARY KEY,
  user_id UUID NOT NULL REFERENCES users (id),
  bio TEXT,
  updated_at TIMESTAMPTZ
);
```

## Touching the record it belongs to

Declare `touch: true` on a comment’s `belongsTo`, as `Comment` does, and creating, updating, destroying, or touching a comment touches its article:

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

const article = await Article.findByOrThrow({ title: "Hello" });
const comment = await article.comments().create({ body: "First!" }); // sets article.updatedAt
await comment.update({ body: "Edited" }); // sets it again
await comment.touch(); // and again
```

- The article’s new time is written in the same atomic batch as the comment. A save with nothing to write doesn’t touch it.
- Changing a comment’s `articleId` touches both the old article and the new one.
- `updateColumns`, `updateAll`, `insert`, and the other bulk writes don’t touch the article, since they run no callbacks.
- A Model without `updatedAt` needs a named attribute. Touching a Model on [another database](/several-databases) throws `InvalidModel`, since the touch couldn’t be written in the same batch.

## Setting another attribute

Name a datetime attribute, as `Reply` does, to set it to the same time as `updatedAt`:

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

const article = await Article.findByOrThrow({ title: "Hello" });
await Reply.create({ articleId: article.id, body: "Agreed" }); // sets updatedAt and lastCommentedAt
```

To set several, list them: `touch: ["lastCommentedAt", "lastActivityAt"]`.

## Running the article’s callbacks

The article is touched as `article.touch()` touches it, so it runs its `afterTouch` callbacks, then its update commit callbacks:

- An article that declares `touch` on its own `belongsTo`, as `Article` does, touches that record too: the comment touches the article, and the article its blog.
- An article the same save creates, such as one built with `comment.article.build()`, is touched after it’s inserted. It runs `afterTouch` and its create commit callbacks, but not the update ones.
- A write touches each record once, however many of its comments touch it.

## Loading the article

The article is loaded before the comment is written, so its callbacks can run. Preload the chain to skip those queries:

```ts
import { Comment } from "./models/comment";

const comments = await Comment.includes({ article: "blog" }).toArray();
for (const comment of comments) await comment.touch(); // no query to load an article or blog
```

- A loaded article sends no query, such as one reached through `article.comments()`. Each level of the chain that isn’t loaded takes one query, and each one waits for the one before it.
- The article is found through the association, so the association’s scope and Article’s default scope apply. An article they hide isn’t touched.
- Inside [`noTouching`](#turning-touches-off), the touch doesn’t load the article.

## Touching with a counter cache

A comment that also keeps a [counter cache](/counter-caches) on the article touches it the same way, in the same batch as the count. An article the default scope hides is counted, but isn’t touched.

## Turning touches off

Run an import in `Article.noTouching` to skip touching the article for each comment:

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

const article = await Article.findByOrThrow({ title: "Hello" });
await Article.noTouching(async () => {
  for (const body of ["One", "Two"]) {
    await Comment.create({ articleId: article.id, body }); // doesn't touch the article
  }
});
await article.touch(); // touch it once, after the import
```

- Inside the block, no article is touched. A comment’s `belongsTo` leaves its article alone, and `article.touch()` writes nothing and resolves to `false`. Once the block ends, articles are touched again.
- `noTouching` covers the Model you call it on and the Models that extend it. To turn off touches for every Model, call `ApplicationRecord.noTouching`.
- It covers only the code the block runs and what that code awaits, so other requests still touch.
- The comments still set their own `updatedAt` when they’re saved. `Article.touchAll()` and `Article.updateCounters(id, counters, { touch: true })` still set the articles’ `updatedAt`. A comment whose `belongsTo` also keeps a counter cache still counts, but doesn’t touch the article.

:::note
Like `withDatabase`, `noTouching` needs [Node.js compatibility](/connecting#using-the-requests-database).
:::

## Touching the record it has

Declare `touch: true` on a user’s `hasOne`, as `User` does, and updating, destroying, or touching a user touches its profile, in the same atomic batch:

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

const user = await User.findByOrThrow({ name: "Sam" });
await user.update({ name: "Sam Smith" }); // sets the user's profile's updatedAt
await user.touch(); // and again
```

- A save with nothing to write doesn’t touch the profile. A `hasOne` through another touches the record it reaches.
- The profile is touched as [a `belongsTo`’s record is](#running-the-articles-callbacks). It takes the names of datetime attributes to set, runs its `afterTouch` and update commit callbacks, and touches its own records in turn.
- It’s found through the association, so a profile the association’s scope or Profile’s default scope hides isn’t touched. Inside [`Profile.noTouching`](#turning-touches-off), it isn’t loaded or touched.
- It isn’t touched when the user is new, when the user’s own save writes it (built through the user, or changed with `autosave: true`), or when the user’s `dependent` removes it with `"destroy"` or `"delete"`. With `"nullify"`, it’s touched once it no longer points at the user.
- A profile saved as its own entry in the user’s batch is still touched, whether it comes before or after the user.

> **Compared with Rails**
>
> Rails’ `touch:` takes `true` or one column. Here it also takes a list of attributes.
>
> Rails does nothing when the article has no `updated_at`, and writes the time to any column you name. Here both throw `InvalidModel` when the Model is first used.
>
> With a counter cache, Rails sets the time in the counter’s `UPDATE` and runs none of the article’s callbacks. Here the article is touched as it is without one, so its `afterTouch` and commit callbacks run.
>
> When a comment moves to another article, Rails finds the old one without the association’s scope. Here the scope applies to both.
>
> When a comment’s `belongs_to` has both `counter_cache:` and `touch:`, Rails’ `no_touching` still touches the article, since the time is set in the counter’s `UPDATE`. Here the article is only counted. Inside the block, Rails’ `touch` returns `nil`, and here it resolves to `false`. Rails also loads each comment’s article for its touch, then leaves it alone. Here the touch doesn’t load it, though a required `belongsTo` still checks that its article exists.
>
> Rails touches a changed profile before its autosave saves it, so its `after_touch` runs too. Here only its save writes it. After a user is created, Rails finds and touches a profile that already points at the new user’s key. Here a new user touches nothing, so a create sends no query for it.
