basecamp / marginalia

Attach comments to ActiveRecord's SQL queries

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

`with_annotation` doesn't work on relations

jacobbednarz opened this issue · comments

While starting to use with_annotation in some of our queries, I am finding that it doesn't work on where methods (and I suspect other AR relation methods).

Rails version: 5.2
Gem version: 1.8.0

# works
Marginalia.with_annotation("foo") { User.first }
#=> SELECT * FROM `users` LIMIT 1 /*foo*/

# works
Marginalia.with_annotation("foo") { User.find_by_id(1) }
#=> SELECT * FROM `users` WHERE `id` = 1 LIMIT 1 /*foo*/

# doesn't
Marginalia.with_annotation("foo") { User.where(id: 1) }
#=> SELECT * FROM `users` WHERE `id` = 1 LIMIT 11

Is this a known thing or any hints as to how to address it?

The reason the last one doesn't appear to work as expected is because the query is actually evaluated when it's returned to pry/irb, not when it's inside the with_annotation block. Adding .to_a to the relation inside the block should make the comment appear.

Yeah sorry this is not a bug.

This will do what you expect for the reasons @stevehodgkiss mentions:

Marginalia.with_annotation("foo") { User.where(id: 1).to_a }

If you're using rails 6+ and you want an annotation to follow your relation then you might like to use #annotate on your relation:

User.where(id: 1).annotate("foo")