How to expire fragment cache when locale changes?

我的梦境 提交于 2019-12-09 11:28:57

问题


I'm trying to use fragment cache to cache the footer and navigation bar on a Ruby on Rails Site that uses I18n. The problem is, changing the language then shows you the footer and navigation bar in the wrong language. How do you go about expiring fragment cache when locale changes?


回答1:


Rather than expiring the fragment cache, you should make the locale part of the cache key, i.e. something like

cache :locale => I18n.locale, ... do
  ...
end

This way different users can see different language versions of the footer/navigation bar but all will see cached versions.




回答2:


When caching a fragment in Rails 3, this did the trick for me:

- cache([object, locale: I18n.locale]) do



回答3:


I use to have this helper, so I don't need to explicitly pass the locale to each cache call:

# frozen_string_literal: true
module CacheHelper
  # Always using current I18n.locale to cache things.
  def cache(name = {}, options = {}, &block)
    name_with_locale = [name].flatten << I18n.locale.to_s
    super(name_with_locale, options, &block)
  end
end


来源:https://stackoverflow.com/questions/10672034/how-to-expire-fragment-cache-when-locale-changes

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