Ruby on Rails: Cómo configurar las opciones de "buscar" para no usar la caché

In Ruby on Rails you can find records from the database with this syntax:


Ejemplos: User.find_by_email('test@test.test'), 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?

preguntado el 08 de enero de 11 a las 22:01

I've not seen caching setup by default... Are you sure? did you check your logs? -

I agree with apneadiving. I don't think it is cached by default. -

2 Respuestas

Puedes usar ActiveRecord::QueryCache.uncached Me gusta esto:

User.find_by_email('test@test.test') # Will return cached result

User.uncached do
  User.find_by_email('test@test.test') # Will query the database again

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        

  User.find_by_email('test@test.test') # Will *not* query database, as we're outside of the Users.uncached block

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') # Will query database

User.do_something # Will run both queries

contestado el 12 de mayo de 16 a las 16:05

I didn't understand how to use these codes: what I have to put instead of 'self.find(...)'? Can you make a practical example? - user502052

I've updated my examples but it's difficult when you're just giving me abstract code. Do you want to use this in a controller or in a model? If controller, you can use my first example. If model, you can use my last. It might be easier if you post what you're trying to do, instead of me trying to come up with examples that make sense to you. - vonconrad

(Note: assuming Rails3, since Rails2 doesn't have default caching.)

This should work as you want it to out of the box:

  1. Queries caches are destroyed after each action ( paragraph 1.5)
  2. In addition, it seems ( that caches are also destroyed on attribute/record updates

Do you have a specific use case not covered by the default configuration?

Respondido el 09 de enero de 11 a las 02:01

I am trying to resolve this problem someway:… - user502052

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.