Everyone should be using low level caching in Rails

jieforest發表於2012-05-20

Low levelcaching is very easy to get started with in Rails 3, but it seems to be missingfrom the official guides.I personally use it all the time to help reduce the number of queries or APIcalls I’m making. Heroku has a pretty goodexplanationwhich, if you’re so far unfamiliar with low-levelcaching, is a good place to start.


Whyshould you use low level caching, and what should you use it for? Maybe youhave some data which you need regularly over multiple pages, e.g. a list ofcategories for your blog. You might want to display them on every page butthey’re not going to need to be entirely up to date for every request. Youcould stick this in controllers/application_controller.rb:


Ifyou haven’t used this style. of caching before, note that I’m calling .all on the Categoryquery. In Rails 3 ActiveRecord now uses lazy loading; it doesn’t perform. thequery until you try to use it. This is great for fragment caching in your viewsas it will prevent that query being called if a fragment cache already exists.However, if you’re using low level caching you’ll want to perform. that queryimmediately so that the results, rather than just the query object you’vebuilt, are stored in the cache.


Themainstay of low level caching in Rails is Rails.cache.fetch. There’s something you need toknow before you end up in a spiral of frustration; by defaultthis will cache in your development environment. Toremedy this, add this line to your config/environments/development.rb:

CODE:

config.cache_store = :null_store

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/301743/viewspace-730272/,如需轉載,請註明出處,否則將追究法律責任。

相關文章