Search code examples
ruby-on-railshibernatedalli

How do cache finding object by id


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.


Solution

  • You can simple use rails's built-in caching

    Rails.cache.fetch :cache_id_here, :expires_in => 1.days do
       Model.find(id)
    end
    

    Change :cache_id_here with whatever you want and set the expiration to your preferences. You can use this caching with memcached or whatever alternative cache store you want. You simply set that in your application config.

    UPDATE

    I'm working on a gem that solves this problem by extending Rail's .find and .save methods and caching results. It's super beta and hasn't been tested in production yet but if you're willing to try it out, take a look at the repo: https://github.com/johnkoht/cache-money-millionaire and let me know your thoughts.

    Essentially if you call Post.find(3) then it will automatically find and create a cached version with a cache key of Post 3 which will automatically be updated on save or touch. Like I said, it's beta but it solves the issue.