To cache the query during a single request, you don't have to do anything besides make sure you're using the ActiveRecord::QueryCache
middleware. If you call it twice:
2.times{ user.native_language.to_s }
You'll see something like this in your log:
Language Load (0.2ms) SELECT `languages`.* FROM `languages` WHERE ...
CACHE (0.0ms) SELECT `languages`.* FROM `languages` WHERE ...
Caching across requests requires manual caching. The identity_cache gem might be useful for what you're trying to do (cache associations).
The quickest way would probably just to add the expires_in
option to the code you have. You can write a generic cached_find
method like the following:
def self.cached_find(id)
key = model_name.cache_key + '/' + id
Rails.cache.fetch(key) do
find(id).tap do |model|
Rails.cache.write(key, model, expires_in: cache_period)
end
end
end
def self.cache_period
3.days
end
You can make it a module mixin to use with as many models as necessary. It does mean you have to write your own association finds. You can also do it with callbacks:
after_commit do
Rails.cache.write(cache_key, self, expires_in: self.class.cache_period)
end