DEV Community

Subash
Subash

Posted on

Rails - annotate method

The annotate method

is used to add an SQL comment to queries generated from the relation. Here is an example

Bullet.includes(:user).
  find_by_id(params[:id])
Enter fullscreen mode Exit fullscreen mode

The above query uses include to eager-load the user table. We can use annotate to add a sql comment to explain the same like

Bullet.includes(:user).
  annotate('Eager loading user table').
  find_by_id(params[:id])
Enter fullscreen mode Exit fullscreen mode

That's it.

Now when you see the rails server logs, you can find the sql comment which was added in the query explanation.

Processing by BulletsController#show as HTML
  Parameters: {"id"=>"5"}
  Bullet Load (0.1ms)  SELECT "bullets".* FROM "bullets" WHERE 
"bullets"."id" = ? /* Eager loading user table */ LIMIT ?
  [["id", 5], ["LIMIT", 1]]
  ↳ app/controllers/bullets_controller.rb:73:in `set_bullet'
  User Load (0.1ms)  SELECT "users".* FROM "users" WHERE
 "users"."id" = ?  [["id", 2]]

Enter fullscreen mode Exit fullscreen mode

Caution: Some escaping is performed, however untrusted user input should not be used.

Source-Code

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay