2010-08-20 44 views
0

我有一个查询,我想要放在我的应用程序的每个页面的页脚上的统计信息。那么自然,我把它在application.rb中,但有问题的统计不全天通常会发生......rails缓存为application.rb

基本上在页脚它会说:

目前,46个国家, 75个城市和20000个地点。

但我想缓存这个查询,所以它不会减慢我的应用程序,它只需要每天更新一次。我将如何做到这一点?

@stat = Location.find(:all, :select => 'COUNT(locations.id) AS locations, COUNT(DISTINCT(city)) AS cities, COUNT(DISTINCT(countries.name)) AS countries', :joins => [ :places, :country ], :conditions => [ 'email IS NOT NULL' ]).first 

回答

0

尝试:

@stat ||= Location.find(:all, :select => 'COUNT(locations.id) AS locations, 
           COUNT(DISTINCT(city)) AS cities, 
           COUNT(DISTINCT(countries.name)) AS countries', 
           :joins => [ :places, :country ], 
           :conditions => [ 'email IS NOT NULL' ]).first 

之后,无效的时间基础上@stat变量,或通过一些其他的事件,就像这样:

@stat = nil 

你也可以做到,通过使用fragment caching

+0

我实际上首先尝试过,但是这似乎并不能在控制器之间运行,即使通过它在应用程序控制器中也是如此。但我做了一个片段缓存,这似乎工作。谢谢! – holden 2010-08-20 10:34:46