Rails 6 adds ActiveRecord::Relation#annotate

Abhay Nikam avatar

Abhay Nikam

July 15, 2019

This blog is part of our  Rails 6 series.

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.


> > 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


> > 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.

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.

Follow @bigbinary on X. Check out our full blog archive.