---
title: "Rails 6 adds ActiveRecord::Relation#annotate"
description:
  "Rails 6 adds ActiveRecord::Relation#annotate to annotate generated SQL
  queries"
canonical_url: "https://www.bigbinary.com/blog/rails-6-adds-annotate-to-activerecord-relation-queries"
markdown_url: "https://www.bigbinary.com/blog/rails-6-adds-annotate-to-activerecord-relation-queries.md"
---

# Rails 6 adds ActiveRecord::Relation#annotate

Rails 6 adds ActiveRecord::Relation#annotate to annotate generated SQL queries

- Author: Abhay Nikam
- Published: July 15, 2019
- Categories: Rails 6, Rails

Rails 6 has added `ActiveRecord::Relation#annotate` to allow adding comments to
the SQL queries generated by the `ActiveRecord::Relation` instance.

Here is how it can be used.

```ruby

> > User.annotate("User whose name starts with 'A'").where("name LIKE ?", "A%")

SELECT "users"._ FROM "users"
WHERE (name LIKE 'A%')
/_ User whose name starts with 'A' \*/
LIMIT ? [["LIMIT", 11]]
```

`ActiveRecord::Relation#annotate` allows to add multiple annotations on a query

```ruby

> > bigbinary = Organization.find_by!(name: "BigBinary")
> > User.annotate("User whose name starts with 'A'")

       .annotate("AND belongs to BigBinary organization")
       .where("name LIKE ?", "A%")
       .where(organization: bigbinary)

SELECT "users"._ FROM "users"
WHERE (name LIKE 'A%') AND "users"."organization_id" = ?
/_ Users whose name starts with 'A' _/
/_ AND belongs to BigBinary organization \*/
LIMIT ? [["organization_id", 1], ["LIMIT", 11]]
```

Also, `ActiveRecord::Relation#annotate` allows annotating scopes and model
associations.

```ruby
class User < ActiveRecord::Base
scope :active, -> { where(status: 'active').annotate("Active users") }
end

> > User.active
> > SELECT "users"._ FROM "users"
> > /_ Active users \*/
> > LIMIT ? [["LIMIT", 11]]
> > ~~~

Check out the
[pull request](https://github.com/rails/rails/pull/35617)
for more details on this.
```

## Links

- [Human page](https://www.bigbinary.com/blog/rails-6-adds-annotate-to-activerecord-relation-queries)
