我使用 Nimir 的帮助找到了这个解决方案。与 Globalize Versioning 一样,您可以为 Active Record 的 Translation 类添加 Paper Trail 支持,但是目前此方法存在一些缺陷。
首先,您需要在 Gemfile 中包含 gem:
gem "i18n-active_record"
gem "paper_trail"
然后您需要确保您的 Translation 模型类继承自 I18n Active Record::Translation 并调用和调用 has_paper_trail:
class Translation < I18n::Backend::ActiveRecord::Translation
has_paper_trail
end
这应该足够了,但是I18n Active Record 中的store_translations 方法不会更新现有记录。相反,每次添加记录时,都会删除具有给定键的所有记录并创建新记录。这会导致 Paper Trail 的混乱,因为它依赖于一个 id。
为了解决这个问题,我创建了自己的store_translation 方法,如果记录存在,它将更新记录:
def store_translations(locale, data, options = {})
escape = options.fetch(:escape, true)
I18n.backend.flatten_translations(locale, data, escape, false).each do |key, value|
t = Translation.find_or_create_by!(locale: locale.to_s, key: key.to_s)
t.value = value
t.save
end
I18n.backend.reload!
end
请注意,我还包括 I18n.backend.reload!,这是因为我正在运行 Memoize 来缓存翻译,但似乎需要告诉它在更新记录时重新缓存。
现在我可以简单地调用:
store_translations(lang, {key => key}, :escape => false)
将新翻译存储到商店,并确保我们保留旧翻译和更改者的记录。