select * from Foo where id = 200
How to cache finding object by id, since we observe a select call being made all the time on a certain id. How should we enable this in rails in a non obtrusive fashion, so that we can switch between any cache store in the future (say memcached or redis)
EDIT:
Much similar to Hibernate based caching strategy  org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE which is applied on all Entity classes in Java EE.
In your Foo model you probably want something like this
class Foo < ActiveRecord::Base
  def self.find_some_foo(foo_id)
    Rails.cache.fetch("foo_#{foo_id}", expires_in: 7.days) do
      begin
        self.where(:id => foo_id)
      rescue Exception => e
        logger.info "Exception fetching Foo ID: #{e.to_s}"
        nil
      end
    end
  end
end
Set up your application’s default cache store by calling config.cache_store= inside your config/application.rb file, for example, config.cache_store = :memory_store The link Alex Ghiculescu provided link has good information in section 2.1.
The rails cache store is automatically populated when you try to fetch a key that doesn't exist in the cache_store. For this reason, it's important to come up with a good naming convention for your keys. Once you have the basics established, it's easy to switch between different cache stores by making the appropriate change in config/application.rb. Some of the choices are memory store, file store, memcache, or any combination of cache stores.
To flush the rails in-memory cache restart your rails server. To flush the file cache, type rake tmp:clear. To flush memcache, see this link.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With