2017-02-26 46 views
0

我使用的public_activity寶石和輸出,我檢查是否可跟蹤所有人是一樣的當前用戶:導軌 - 的提高性能反覆if語句

= 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) 

有什麼辦法可以加速條件嗎?

回答

1

你不應該需要加載的用戶記錄,只是比較ID屬性

= a.owner_id == current_user.id ? 'You' : a.owner.name 

緩存調用可能仍會發生,如果多個活動所有者不是當前用戶(得到所有者名稱)。

2

@jverban是正確的,您可以比較記錄ID以避免不必要的記錄加載。爲了回答你關於急切加載的問題,是的,你可以使用ActiveRecord查詢鏈中的includes方法進行加載。例如:

Activity.includes(:owner).latest 

這將告訴Rails你打算引用owner關係,因此他們應該被加載爲好。

我強烈建議在您的項目(僅限於開發和測試環境)中添加bullet gem來檢測N + 1查詢,並在發生此類N + 1查詢情況時發出警告。

+0

我已經這樣做了,並且已經有了這個寶石。謝謝。 – Ish