Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails.cache-工作但不工作_Ruby On Rails_Ruby On Rails 3_Memcached_Dalli - Fatal编程技术网

Ruby on rails Rails.cache-工作但不工作

Ruby on rails Rails.cache-工作但不工作,ruby-on-rails,ruby-on-rails-3,memcached,dalli,Ruby On Rails,Ruby On Rails 3,Memcached,Dalli,我正在使用Rails.cache(我在dalli gem中尝试了默认存储和memcached,但我得到了相同的行为),它似乎可以工作,但不能工作(日志显示没有进行查询,但实际结果显示不是这样)。。。我有一个搜索页面,可将前十个查询缓存一天: search.rb def self.top_ten Rails.cache.fetch("top_ten_searches_cache", :expires_in => 1.day) do Search.order("coun

我正在使用Rails.cache(我在dalli gem中尝试了默认存储和memcached,但我得到了相同的行为),它似乎可以工作,但不能工作(日志显示没有进行查询,但实际结果显示不是这样)。。。我有一个搜索页面,可将前十个查询缓存一天:

search.rb

  def self.top_ten
    Rails.cache.fetch("top_ten_searches_cache", :expires_in => 1.day) do
      Search.order("count DESC").limit(10)
    end    
  end 
然而,当我进入搜索页面,输入一个新的搜索词,重复,它开始显示在前十名的结果!(然而,我不希望前十名结果在1天内改变。)当缓存存储为默认值时,日志中不会显示任何查询(因此您认为缓存正在工作),当使用dalli/memcached时,我会得到完全相同的行为,但日志中有以下内容:

Cache read: top_ten_searches_cache ({:expires_in=>1 day})
Cache fetch_hit: top_ten_searches_cache ({:expires_in=>1 day})
Cache fetch\u hit
的确切含义是什么?这是否意味着找不到缓存并且必须执行查询


不太确定发生了什么-奇怪的是,我在默认存储区或使用Dalli的memcached中得到了相同的行为。

您正在缓存范围,而不是查询的实际结果。Rails使用延迟加载,因此要强制执行查询,您需要将
.to_a
(或Rails 3中的
.all
),例如:

def self.top_ten
  Rails.cache.fetch("top_ten_searches_cache", :expires_in => 1.day) do
    Search.order("count DESC").limit(10).to_a
  end    
end 

瞧。

嗨,迈克-谢谢,我怎么会忘记呢!我已经按照您的示例更改了查询,但是,我仍然得到相同的行为-如果我搜索一个新术语大约五次,它将显示在前十名列表中,并且我不希望在24小时内发生更改(因为它应该返回缓存的值)。我还做错什么了吗?啊,我想我知道发生了什么。。。我需要刷新缓存,因为它保存的是旧值。。。