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('[email protected]')
, User.find_by_id(1)
, ...
Time ago, if I am not wrong, I read somewhere that you 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('[email protected]')
User.find_by_email('[email protected]') # Will return cached result
User.uncached do
User.find_by_email('[email protected]')
User.find_by_email('[email protected]') # 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('[email protected]')
@another_user = User.find_by_email('[email protected]') # Will query database
end
User.find_by_email('[email protected]') # 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('[email protected]')
self.find_by_email('[email protected]') # Will query database
end
end
end
User.do_something # Will run both queries
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