This blog is part of our Rails 6 series. Rails 6.0 was recently released.

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 for more details on this.