Ruby on Rails: How to set up "find" options in order to not use cache
In Ruby on Rails you can find records from the database with this syntax:
<model_name>.find_by_<field_name>()
Examples: User.find_by_email('test@test.test')
, User.find_by_id(1)
, ...
Time ago, if I am not wrong, I read somewhere that 开发者_如何学JAVAyou can explicitly disable caching for 'find' operations, but I can not remember how.
Can someone help me remember?
You can use ActiveRecord::QueryCache.uncached
like this:
User.find_by_email('test@test.test')
User.find_by_email('test@test.test') # Will return cached result
User.uncached do
User.find_by_email('test@test.test')
User.find_by_email('test@test.test') # Will query the database again
end
In a controller, it would look something like this:
def show # users#index action
User.uncached do
@user = User.find_by_email('test@test.test')
@another_user = User.find_by_email('test@test.test') # Will query database
end
User.find_by_email('test@test.test') # Will *not* query database, as we're outside of the Users.uncached block
end
Obviously, in a model, you just have to do:
class User < ActiveRecord::Base
def self.do_something
uncached do
self.find_by_email('test@test.test')
self.find_by_email('test@test.test') # Will query database
end
end
end
User.do_something # Will run both queries
(Note: assuming Rails3, since Rails2 doesn't have default caching.)
This should work as you want it to out of the box:
- Queries caches are destroyed after each action ( http://guides.rubyonrails.org/caching_with_rails.html paragraph 1.5)
- In addition, it seems (http://ryandaigle.com/articles/2007/2/7/what-s-new-in-edge-rails-activerecord-explicit-caching) that caches are also destroyed on attribute/record updates
Do you have a specific use case not covered by the default configuration?
精彩评论