Rails 4 low-level caching not working

849 views Asked by At

I think is not working because I test it with a real db situation, and always returns the content of db

  1. Execute the Rails.cache.fetch
  2. Modify the database
  3. Execute again the Rails.cache.fetch, and here It not should return the new value that I've modified in db. but it happens, not caching is executed

    class Translation < ActiveRecord::Base

    def self.translate(es_text,locale=I18n.locale)
    
      Rails.cache.fetch("#{es_text}/#{locale}", expires_in: 1.month) do
        trad=self.find_by_es_text(es_text)
        translated=eval("trad.#{locale}_text")
        return translated if translated.present?
      end
    
    end
    

    end

The test:

I Execute Translation.translate('Alojamiento','en') and it returns what finds on DB : "Accomodation"

Then I modify the database table replacing "Accomodation" with "Accomodation---", and commit,...

Come back to Rails, execute the same Translation.translate('Alojamiento','en') and it returns the new value "Accomodation---" !!!

But it shouldn't!! isn't it? Because I have put expires_in: 1.month not in 1.second

Or, Does Rails know when database is modified, and expire cache automatically?

I think the cache is not working, or maybe I'm missing some configuration

Thanks a lot


  • One way to make "it works" (but I don't like) is moving the Rails.cache... code in a method controller, and call a url like www.app/translate/Alojamiento?locale=en. In this case it works, but caching in a model is more correct.

    class ApplicationController < ActionController::Base
      ...  
      def translate
        text_return=Rails.cache.fetch("#{params[:es_text]}/#{params[:locale]}", expires_in: 1.month) do
          Translation.translate(params[:es_text],params[:locale])
        end
        render text: text_to_return
      end
    
1

There are 1 answers

1
Albert Català On

The solution is in put the cache result in a variable, and return it

IT seems is not the same, this:

def self.translate(es_text,locale=I18n.locale)
  retorn_text=Rails.cache.fetch("#{es_text}/#{locale}", expires_in: 1.month) do
    trad=self.find_by_es_text(es_text)

    eval("trad.#{locale}_text")
  end

  retorn_text 
end

than this:

def self.translate(es_text,locale=I18n.locale)
  Rails.cache.fetch("#{es_text}/#{locale}", expires_in: 1.month) do
    trad=self.find_by_es_text(es_text)

    eval("trad.#{locale}_text")
  end
end

But I don't understand why