问题
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