views:

22

answers:

1

I have a query that pulls stats which I would like to place on the footer of every page of my application. So natural I'm putting it in the application.rb, but the statistics in question don't change throughout the day generally...

Basically in the footer it will say:

Currently, 46 Countries, 75 Cities, and 20,000 locations.

But I would like to cache this query so it doesn't slow down my app, it only needs to update maybe once per day. How would I do this?

@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
A: 

Try:

@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

After that, invalidate the @stat variable on the time basis, or by some other events, like this:

@stat = nil

You can also accomplish that by using fragment caching.

floatless
i actually tried that first, but that doesn't seem to work going between controllers, even through it's in the application controller. But I did a fragment cache and that seems to work. Thanks!
holden