在我的Rails 4应用程序的home_controller中,我执行一个自定义的SQL查询并将结果保存到一个实例变量中
@studentscoring = ActiveRecord::Base.connection.execute sql_string_student
然后,在配置开发config.action_controller.perform_caching = true中将缓存设置为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 %>
刷新浏览器三次显示查询运行三次,查询的最后一次运行比第一次运行的时间要长.7ms,所以我假定缓存不工作,或者我没有正确的做到这一点:).你能告诉我我做错了什么吗?
不是任何标准的专家,我不明白缓存可以从<%缓存... 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
第3
(1.8ms) with cte_scoring as ( select users.id,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)