Rails 4 low-level caching not working

无人久伴 提交于 2021-01-28 14:43:54

问题


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:


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



来源:https://stackoverflow.com/questions/30739267/rails-4-low-level-caching-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!