We write about Ruby on Rails, React.js, React Native, remote work, open source, engineering and design.
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.
1
2> > User.annotate("User whose name starts with 'A'").where("name LIKE ?", "A%")
3
4SELECT "users"._ FROM "users"
5WHERE (name LIKE 'A%')
6/_ User whose name starts with 'A' \*/
7LIMIT ? [["LIMIT", 11]]
ActiveRecord::Relation#annotate
allows
to add multiple annotations on a query
1
2> > bigbinary = Organization.find_by!(name: "BigBinary")
3> > User.annotate("User whose name starts with 'A'")
4
5 .annotate("AND belongs to BigBinary organization")
6 .where("name LIKE ?", "A%")
7 .where(organization: bigbinary)
8
9SELECT "users"._ FROM "users"
10WHERE (name LIKE 'A%') AND "users"."organization_id" = ?
11/_ Users whose name starts with 'A' _/
12/_ AND belongs to BigBinary organization \*/
13LIMIT ? [["organization_id", 1], ["LIMIT", 11]]
Also, ActiveRecord::Relation#annotate
allows annotating scopes and model
associations.
1class User < ActiveRecord::Base
2scope :active, -> { where(status: 'active').annotate("Active users") }
3end
4
5> > User.active
6> > SELECT "users"._ FROM "users"
7> > /_ Active users \*/
8> > LIMIT ? [["LIMIT", 11]]
9> > ~~~
10
11Check out the
12[pull request](https://github.com/rails/rails/pull/35617)
13for more details on this.