2

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).

I replace my query with this:

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

But it raises an exception:

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

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
JohnMerlino
  • 3,900
  • 4
  • 57
  • 89

1 Answers1

6

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 }

...or...

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

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

Veraticus
  • 15,944
  • 3
  • 41
  • 45
  • the problem is I need an active relation back in order to filter the results with where clauses and kaminari – JohnMerlino Mar 18 '13 at 19:05
  • This was correct in the sense that it doesn't work unless it's an array. Im still having some troubles that I framed in another question: http://stackoverflow.com/questions/15527678/ruby-on-rails-and-kaminari – JohnMerlino Mar 20 '13 at 15:24