Q:

Rails - Increasing performance of repeated if statement

I'm using the public_activity gem and in the output, I'm checking if the trackable owner is the same as the current user:
= a.owner == current_user ? 'You' : a.owner.name
did this activity

I get a bunch of cache calls in the log:
  User Load (1.8ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  Rendered public_activity/post/_create.html.haml (1.4ms)
  Rendered public_activity/_snippet.html.haml (11.4ms)
  CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  Rendered public_activity/post/_create.html.haml (13.9ms)
  Rendered public_activity/_snippet.html.haml (18.9ms)
  CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  Rendered public_activity/comment/_comment.html.haml (0.9ms)
  Rendered public_activity/_snippet.html.haml (12.1ms)
  CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  Rendered public_activity/comment/_comment.html.haml (2.7ms)
  Rendered public_activity/_snippet.html.haml (56.3ms)
  CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  Rendered public_activity/comment/_comment.html.haml (0.6ms)
  Rendered public_activity/_snippet.html.haml (4.5ms)
  CACHE (0.0ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2  [["id", 1], ["LIMIT", 1]]
  Rendered public_activity/content/_comment.html.haml (2.1ms)
  Rendered public_activity/_snippet.html.haml (9.5ms)

Is there any way to eager load the conditional?

A:

You shouldn't need to load the user record, just compare id attributes
= a.owner_id == current_user.id ? 'You' : a.owner.name

The cache calls will likely still happen if multiple activity owners are not the current user (to get the owner name).

