rails - using Rails.cache gives error

时间秒杀一切 提交于 2020-02-22 15:26:10

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/15442194/rails-using-rails-cache-gives-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!