【问题标题】:Rails: Model.human_attribute_name :field should raise an error when translation not found? (Maybe caused by state_machine?)Rails:Model.human_attribute_name :field 应该在找不到翻译时引发错误? (可能是由 state_machine 引起的?)
【发布时间】:2014-01-07 16:24:00
【问题描述】:

我们经常在我们的应用程序中偶然发现未翻译的模型属性。他们最常出现是因为属性被重命名或类似的东西。

Model.human_attribute_name :field 找不到翻译时,让 I18n 引发错误真的很有帮助。有没有办法做到这一点?

更新

似乎还有其他问题。这是我的 I18n 设置:

I18n.enforce_available_locales = false
config.i18n.load_path += Dir[Rails.root.join('config', 'locales', '**', '*.{rb,yml}')]
config.i18n.default_locale = 'de-CH'
config.i18n.available_locales = ['de', 'de-CH', 'en']
config.i18n.locale = 'de-CH'
config.i18n.fallbacks = {'de-CH' => 'de', 'en-GB' => 'en'}

我无法设置fallbacks = false,因为我希望缺少de-CH 的翻译以优雅地委托给de,这通常看起来工作正常。但是对于我的state machine 属性human_to_state 方法,它似乎不起作用。这是导致问题的视图代码:

= f.input :state_event, collection: f.object.state_transitions,
                        label_method: :human_to_name # This causes the problem!

这在视图中打印为“状态事件”,当我添加以下 I18n 键时,它已成功转换为“状态”:

de: 类: 属性: 活动: state_event: 状态

所以确实翻译缺失,但 I18n 并没有以任何方式抱怨。我还尝试使用自定义异常处理程序捕获异常,但这似乎没有引发:

I18n.exception_handler = lambda do |exception, locale, key, options|
  binding.pry # This is never reached!
end

知道发生了什么吗?是状态机的问题吗?

【问题讨论】:

标签: ruby-on-rails state-machine rails-i18n


【解决方案1】:

问题在于human_attribute_name 回退到

defaults << attribute.to_s.humanize

当没有其他发现时。换句话说,human_attribute_name 永远不会引发错误。

我通过覆盖 human_attribute_name 来“修复”这个问题,修补上述行:

(将其放入初始化程序中)

require 'active_support/core_ext/hash/reverse_merge'

module ActiveModel
  module Translation
    include ActiveModel::Naming

    def human_attribute_name(attribute, options = {})
      defaults = lookup_ancestors.map do |klass|
        [:"#{self.i18n_scope}.attributes.#{klass.model_name.i18n_key}.#{attribute}",
         :"#{self.i18n_scope}.attributes.#{klass.model_name.i18n_key.to_s.tr('.', '/')}.#{attribute}"]
      end.flatten

      defaults << :"attributes.#{attribute}"
      defaults << options.delete(:default) if options[:default]
      defaults << attribute.to_s.humanize if Rails.env.production? # Monkey patch

      options.reverse_merge! :count => 1, :default => defaults
      I18n.translate(defaults.shift, options)
    end
  end
end

【讨论】:

    【解决方案2】:

    可能重复:How to enable Rails I18n translation errors in views?

    接受的答案是:

    config.i18n.fallbacks = false
    

    @BettySt 的回答也很酷,你应该看看她的解决方案。

    有关如何处理 I18n 翻译错误的文档: http://guides.rubyonrails.org/i18n.html#using-different-exception-handlers

    【讨论】:

    • 谢谢你指点我,一开始没找到。
    • 我在我的问题中添加了更多细节,因为我无法用提供的信息解决它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    • 1970-01-01
    • 2018-06-06
    相关资源
    最近更新 更多