Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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('[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?

like image 311
user502052 Avatar asked Jan 08 '11 22:01

user502052


1 Answers

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
like image 176
vonconrad Avatar answered Sep 28 '22 10:09

vonconrad