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

Top comments (0)