Rails 4低级缓存无法正常工作

时间:2015-06-09 17:47:58

标签: ruby-on-rails-4 caching

我认为无法正常工作,因为我使用真实的数据库情况对其进行测试,并始终返回db

的内容
  1. 执行Rails.cache.fetch
  2. 修改数据库
  3. 再次执行Rails.cache.fetch,此处应返回我在db中修改过的新值。但它发生了,而不是执行缓存

    class Translation<的ActiveRecord ::基

    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
    

  4. 测试:

    我执行Translation.translate('Alojamiento','en')并返回在DB上找到的内容:"Accomodation"

    然后我修改数据库表替换" Accomodation"与"住宿---",并提交,......

    回到Rails,执行相同的Translation.translate('Alojamiento','en')并返回新值"Accomodation---" !!!

    但它不应该!!不是吗?因为我已将expires_in: 1.month放入1.second

    或者,Rails是否知道数据库何时被修改,并自动使缓存过期?

    我认为缓存不起作用,或者我可能缺少某些配置

    非常感谢

    • 制作的一种方法"它起作用" (但我不喜欢)正在移动方法控制器中的Rails.cache...代码,并调用类似www.app/translate/Alojamiento?locale=en的网址。 在这种情况下它可以工作,但模型中的缓存更正确。

      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 个答案:

答案 0 :(得分:0)

解决方案是将缓存结果放入变量中,并将其返回

IT似乎不一样,这个:

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)
    translated=eval("trad.#{locale}_text")
    return translated?
  end
  return retorn_text 
end

比这个:

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
  end

end

但我不明白为什么