Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 334
Joe Avatar asked Mar 12 '13 11:03

Joe


1 Answers

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.

like image 185
Gui LeFlea Avatar answered Sep 18 '22 17:09

Gui LeFlea