2016-03-31 62 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

它已被激活。 –

相关问题