我正在使用public_activity gem并在输出中,我正在检查可跟踪所有者是否与当前用户相同:
= a.owner == current_user ? 'You' : a.owner.name
did this activity
我在日志中收到了一堆缓存调用:
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)
有没有办法急于加载条件?
答案 0 :(得分:2)
@jverban是正确的,你可以比较记录ID,以避免不必要的记录加载。要回答关于急切加载的问题,是的,您可以使用ActiveRecord查询链中的includes
方法急切加载。例如:
Activity.includes(:owner).latest
这将告诉Rails你打算引用owner
关系,所以它们也应该被加载。
我强烈建议将bullet gem添加到您的项目中(仅在开发和测试环境中)以检测N + 1个查询,并在您遇到N + 1查询情况时发出警告。< / p>
答案 1 :(得分:1)
您不需要加载用户记录,只需比较id属性
= a.owner_id == current_user.id ? 'You' : a.owner.name
如果多个活动所有者不是当前用户(获取所有者名称),则可能仍会发生缓存调用。