CONCEPT Cited by 1 source
ActiveRecord annotate method¶
Definition¶
annotate is a method on Rails 7+ ActiveRecord relations that
adds a SQL comment to a specific query. It is the per-query
override complementing Rails's per-request
query_log_tags mechanism.
Syntax¶
Emits:
The comment is placed inline with the query rather than on the
trailing line — a different attachment convention from
query_log_tags, though both end up as inert SQL comments the
database ignores and the query-log consumer parses.
Why it exists¶
The built-in Rails 7 query log tags cover per-request metadata (controller, action, job, application) automatically for every query in the request. But some queries need attribution that doesn't come from request context:
- Background job with sub-task identity. A single Sidekiq job
runs 20 different query patterns; the
jobtag identifies the job class but not which specific sub-task emitted each query. - Rake tasks and scripts. Rails
query_log_tagsdoesn't auto-populate inrakeorrails runnercontexts;annotatelets the task author tag queries explicitly. - Library code. A gem issuing queries on behalf of the application may want to mark queries with its own identifier regardless of the application's request context.
- Correlation IDs. Attach a request-ID or trace-ID to a specific query for post-hoc join with external systems.
Canonical framing from the source post: "If you need even more detail for a specific query, Rails 7 also added the annotate method, which lets you add a comment to a query" (Source: sources/2026-04-21-planetscale-identifying-slow-rails-queries-with-sqlcommenter).
Composition with query_log_tags¶
Both mechanisms emit SQL comments attached to the same query
string. A query issued during a request with
query_log_tags_enabled = true that also uses annotate will
carry both comments — the per-request baseline + the per-query
override. The consuming query-log parser (PlanetScale Insights,
Google Cloud SQL Insights, application log readers) sees both
annotations on the same query.
Format is author-controlled¶
Unlike query_log_tags (which has a configurable emission format
between Rails-default and SQLCommenter), annotate passes the
caller-provided string through essentially unchanged — the caller
is responsible for its format. To emit SQLCommenter-compatible
annotate tags, the caller writes annotate("key='value'")
rather than annotate("key:value").
Seen in¶
- sources/2026-04-21-planetscale-identifying-slow-rails-queries-with-sqlcommenter
— canonical wiki introduction. Coutermarsh + Ekechukwu
(2022-06-29) frame
annotateas the per-query escape hatch on top of the per-requestquery_log_tagsbaseline: "This is useful in situations where the default query log tags aren't enough." The worked example (User.where(name: "iheanyi").annotate("source='user_metrics_runner'")) emitssource='user_metrics_runner'in SQLCommenter format, making it observable to PlanetScale Insights's SQLCommenter parser.