我认为这是行不通的,因为我是在真实的db环境下进行测试的,并且始终返回db的内容
I think is not working because I test it with a real db situation, and always returns the content of db
再次执行 Rails.cache.fetch ,在这里不应该返回我在db中修改的新值.但它发生了,没有执行缓存
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
类翻译<ActiveRecord :: Base
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 endend
测试:
我执行 Translation.translate('Alojamiento','en'),它返回在DB上找到的内容:住宿"
I Execute Translation.translate('Alojamiento','en') and it returns what finds on DB : "Accomodation"
然后我修改数据库表,将"Accomodation"替换为"Accomodation ---",然后提交,...
Then I modify the database table replacing "Accomodation" with "Accomodation---", and commit,...
回到Rails,执行相同的 Translation.translate('Alojamiento','en'),它会返回新值"Accomodation ---" !!!
Come back to Rails, execute the same Translation.translate('Alojamiento','en') and it returns the new value "Accomodation---" !!!
但这不应该!!是不是,因为我将 expires_in:1.month 放在了 1.second
或者,Rails是否知道何时修改数据库并自动使缓存过期?
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
非常感谢
-
一种使它起作用"的方法(但我不喜欢)是在方法控制器中移动 Rails.cache ... 代码,并调用 www.app/translate/Alojamiento?locale=en .在这种情况下,它可以工作,但是在模型中进行缓存更加正确.
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.
解决方案是将缓存结果放入变量中,然后将其返回
The solution is in put the cache result in a variable, and return 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) eval("trad.#{locale}_text") end 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) eval("trad.#{locale}_text") end end但是我不明白为什么
更多推荐
Rails 4低级缓存不起作用
发布评论