【问题标题】:rails4 after caching query still runs缓存查询后的rails4仍然运行
【发布时间】:2016-07-19 20:20:27
【问题描述】:

我有一个 rails 4 应用程序并尝试实现缓存。我使用@profiles_sidebar.first 缓存键来检查是否创建了新用户。我不确定这是否可以,因为仍然有一个数据库查询。这是检查缓存是否需要过期的首选机制吗?我过得好吗?

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

【问题讨论】:

    标签: ruby-on-rails caching fragment-caching


    【解决方案1】:

    没有办法绕过至少一个数据库查询,因为您需要知道自创建摘要以来记录是否已更新。

    您可以预先加载 @profiles_sidebar 侧边栏,这在“冷”缓存上会更好一些,因为它是单个数据库查询:

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

    不过,获取单条记录和获取 10 条记录之间的实际差异可能很小。

    您可能还想使用eager loading or includes 在一个查询中同时获取用户和个人资料:

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

    【讨论】:

    【解决方案2】:

    我想你是在开发环境中,你确定你已经激活了rails中的缓存吗? (默认情况下它对开发环境禁用)

    确保你的 development.rb 中有这一行

    config.action_controller.perform_caching = true
    

    【讨论】:

      猜你喜欢
      • 2012-07-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-12
      • 2012-01-26
      • 2022-11-19
      • 2015-06-18
      相关资源
      最近更新 更多