在我的 Rails 4 应用程序的 home_controller 中,我执行自定义 sql 查询并将结果保存到实例变量
@studentscoring = ActiveRecord::Base.connection.execute sql_string_student
然后,我在配置开发中将缓存设置为 trueconfig.action_controller.perform_caching = true
并重新启动应用程序后,围绕视图中的相关变量设置缓存。
<% cache @studentscoring do%>
<% for lawyer in @studentscoring %>
<div class="span2">
<div class="row">
<%= tiny_gravatar_for lawyer['name'], lawyer['email'] %>
</div>
...... #code ommitted
</div>
<% end %>
<% end %>
刷新浏览器 3 次表明查询运行了 3 次,最后一次运行实际上比第一次多 0.7 毫秒,所以我假设缓存不起作用或者我没有正确执行 :)。你能告诉我我做错了什么吗?
不是任何标准的专家,我不明白如何使用 <% cache ... do %> 语法从视图触发缓存,因为在加载视图时还没有控制器查询运行,因此告诉 Rails 使用缓存副本为时已晚?
从服务器日志...
第一的
(1.1ms) with cte_scoring as (
select
users.id, users.name, users.email,
(select Coalesce(sum(value),0) from answer_votes where (answer_votes.user_id = users.id) AND (created_at >= Current_Date - interval '7 day')) +
(select Coalesce(sum(value),0) from best_answers where (best_answers.user_id = users.id) AND (created_at >= Current_Date - interval '7 day')) +
(select Coalesce(sum(value),0) from contributions where (contributions.user_id = users.id) AND (created_at >= Current_Date - interval '7 day')) total_score
from
users
where
users.student = 'true')
select id,
name,
email,
total_score
from cte_scoring
order by total_score desc
limit 5
第三
(1.8ms) with cte_scoring as (
select
users.id, users.name, users.email,
(select Coalesce(sum(value),0) from answer_votes where (answer_votes.user_id = users.id) AND (created_at >= Current_Date - interval '7 day')) +
(select Coalesce(sum(value),0) from best_answers where (best_answers.user_id = users.id) AND (created_at >= Current_Date - interval '7 day')) +
(select Coalesce(sum(value),0) from contributions where (contributions.user_id = users.id) AND (created_at >= Current_Date - interval '7 day')) total_score
from
users
where
users.student = 'true')
select id,
name,
email,
total_score
from cte_scoring
order by total_score desc
limit 5
更新
日志显示它正在读取一个片段(在上面的查询运行之后),那么为什么查询会有不同的时间并且后面的查询会更慢呢?如果有要读取的片段,我会认为根本不会运行查询。
Read fragment views/id/75/name/Retarded Student/email/retarstudent@gmail.com/total_score/0/id/83/name/Jim Beam/email/jimbean@gmail.com/total_score/0/id/79/name/Weird Student/email/weirdstudent@gmail.com/total_score/0/id/80/name/VegetableSTudent/email/veggiestudent@gmail.com/total_score/0/c9638e467bfd0fbf5b619ab411182256 (0.3ms)