加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 可以在Rails中缓存自定义的sql查询吗?

发布时间:2020-12-16 22:29:19 所属栏目:百科 来源:网络整理
导读:在我的Rails 4应用程序的home_controller中,我执行一个自定义的sql查询并将结果保存到一个实例变量中 @studentscoring = ActiveRecord::Base.connection.execute sql_string_student 然后,在配置开发config.action_controller.perform_caching = true中将缓
在我的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)

解决方法

将查询结果缓存在控制器中.您可以在一次调用中读取或写入高速缓存(即,将缓存中的数据设置为不存在)
def index
  @studentscoring = Rails.cache.fetch("your_cache_key",:expires_in => 5.minutes) do
    ActiveRecord::Base.connection.select_rows(sql_string_student)
  end
end

所以上面将首先检查缓存中的“your_cache_key”,如果数据存在将从高速缓存返回.如果它不存在,块将被执行,并且它将被设置在缓存中

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读