缓存查询后的rails4仍然运行 [英] rails4 after caching query still runs

查看:87
本文介绍了缓存查询后的rails4仍然运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a rails 4 app and trying to implement caching. I use the @profiles_sidebar.first cache key for checking if new user was created. I'm not sure if this is ok, since there still is a db query. Is this the preferred mechanism to check if caching needs to be expired? Am I doing well?

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

读取缓存时的控制台代码:

console code when reading cache:

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)

推荐答案

无法解决至少一个数据库查询,因为您需要知道自创建摘要以来记录是否已更新.

There is no way of getting around at least one database query since you need to know if the record has been updated since the digest was created.

您可以预先加载@profiles_sidebar侧边栏,由于它是单个数据库查询,因此在冷"高速缓存上会更好一些:

You could load @profiles_sidebar sidebar upfront which would be somewhat better on a "cold" cache since its a single DB query:

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

尽管获取一条记录和10条记录之间的实际差异可能很小.

The actual difference between fetching a single record and 10 may be marginal though.

您可能还想使用

You also may want to use eager loading or includes to fetch both User and Profile in one query:

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

这篇关于缓存查询后的rails4仍然运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆