Low-level caching

suggest change

Rails.cache, provided by ActiveSupport, caches serializable Ruby objects across requests. This is low-level caching. View fragment caching is the cache helper in a template.

To fetch a value from the cache for a given key, use cache.read:

Rails.cache.read('city')
# => nil

Use cache.write to write a value to the cache:

Rails.cache.write('city', 'Duckburgh')
Rails.cache.read('city')
# => 'Duckburgh'

Alternatively, use cache.fetch to read a value from the cache and optionally write a default if there is no value:

Rails.cache.fetch('user') do
  User.where(is_awesome: true).to_a
end

The return value of the block is stored under the given key and then returned. Cache the loaded records. A relation is a poor cache entry: the query runs when it is loaded, and most cache stores cannot round-trip the relation object.

You can also specify a cache expiry:

Rails.cache.fetch('user', expires_in: 30.minutes) do
  User.where(is_awesome: true).to_a
end

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents