本文介绍了rails-使用Rails.cache会出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在Rails 3中缓存一个昂贵的查询,该查询可在整个站点的多个请求中重复使用。

I'm trying to cache an expensive query that is reused in several requests throughout the site in Rails 3.

当用户单击表以查看报告或当用户单击以查看地图或单击以打印内容时,将执行以下查询:

When a user clicks a table to view reports or when a user clicks to view a map or when a user clicks to print something, this query is performed:

reports.where{(time > my{range.begin}) & (time < my{range.end})}

这是一个昂贵的查询,可能导致成千上万的查询记录。我想缓存它,以便在第一次调用它之后将其存储在缓存中,直到查询中的一条记录被修改(例如更新)为止。

It's an expensive query that can result in thousands of records. I want to cache it so after the first time it is called, it is stored in the cache until one of the records in the query is modified (e.g. updated).

我将查询替换为:

Rails.cache.fetch('time_reports') { reports.where{(time > my{range.begin}) & (time < my{range.end})} }

但这会引发一个例外:

TypeError (can't dump anonymous class #<Module:0x007f8f92fbd2f8>):

作为问题的一部分,我想知道是否使用Rails.cache.fetch还需要我在config / environments / production中添加以下内容。 rb:

As part of the question, I would like to know if using Rails.cache.fetch also requires me to add the following in config/environments/production.rb:

config.cache_store = :mem_cache_store, "cache-1.example.com", "cache-2.example.com" //obviously I would use my ip


推荐答案

您尝试将Arel关系转储到您的缓存存储中,这是不可能的。您想转储生成的数组,请改为这样做:

You're trying to dump an Arel relation into your cache store, which unfortunately is not possible. You want to dump the resulting array, so do this instead:

Rails.cache.fetch('time_reports') { reports.where{(time > my{range.begin}) & (time < my{range.end})}.all }

.....

Rails.cache.fetch('time_reports') { reports.where{(time > my{range.begin}) & (time < my{range.end})}.to_a }

这将导致与变成一个真实的数组,您可以按照常规将其存储在memcached中。

That will cause the relation to become a real array, which you can store in memcached as per normal.

这篇关于rails-使用Rails.cache会出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 00:55