2016-03-31 60 views
0

我有一個rails 4應用程序,並試圖實現緩存。我使用@profiles_sidebar.first緩存鍵來檢查是否創建了新用戶。我不確定這是否正常,因爲仍然有一個數據庫查詢。這是檢查緩存是否需要過期的首選機制?我做得好嗎?緩存後,rails4仍然運行

<% cache(@profiles_sidebar.first) do %> 
    <% @profiles_sidebar.each do |profile| %> 
    <%= link_to user_path(profile.user) do %>    
     <%= truncate(profile.full_name, length: 25) %> 
     <%= truncate(profile.company, length:25) %> 
    <% end %> 
    <% end %> 
<% end %> 
讀取緩存時

控制檯代碼:

13:31:53 puma.1 | Profile Load (2.2ms) SELECT "profiles".* FROM "profiles" ORDER BY "profiles"."created_at" DESC LIMIT 1 
13:31:53 puma.1 | User Load (2.2ms) SELECT "users".* FROM "users" WHERE "users"."id" IN (67) 
13:31:53 puma.1 | Cache digest for app/views/users/_user_sidebar.html.erb: bfc9447057c94bcfe13c18e391127f2d 
13:31:53 puma.1 | Read fragment views/profiles/62-20160331112332689423000/bfc9447057c94bcfe13c18e391127f2d (0.2ms) 
13:31:53 puma.1 | Rendered users/_user_sidebar.html.erb (11.8ms) 

回答

1

沒有,因爲你需要知道,如果因爲消化創建記錄已更新讓周圍至少一個數據庫查詢的方式。

您可以加載@profiles_sidebar欄前期這將是稍微好一個「冷」緩存,因爲它是一個單一的數據庫查詢:

@profiles_sidebar = Profile.order(created_at: :desc) 
          .limit(10) 
          .load 

獲取單個記錄和10之間的實際差異可能是邊際雖然。

您可能還需要使用eager loading or includes在一個查詢中獲取User和個人資料:

@profiles_sidebar = Profile.includes(:user) 
          .order(created_at: :desc) 
          .limit(10) 
          .load 
+0

最大,謝謝。我還會再提出一個問題,因爲我對某些東西還不確定。 –

+0

這是關於命名緩存鍵的新命令:http://stackoverflow.com/questions/36336322/rails4-caching-naming-conventions –

0

我想你是在開發環境中,你確定你已經激活軌道緩存?再次(默認情況下它被用於開發ENV禁用)

請確保您有這條線在你的development.rb

config.action_controller.perform_caching = true 
+0

它已被激活。 –

相關問題