Rails:Model.human_attribute_name:字段应该在找不到翻译时引发错误? (也许是由state_machine引起的?)

我们经常在应用程序中偶然发现未翻译的模型属性。 它们通常是因为某个属性被重命名或类似的东西而来。

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 ,这通常似乎工作正常。 但是对于我的状态机属性human_to_state方法,它似乎不起作用。 这是导致问题的视图代码:

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

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

de:mongoid:attributes:activity:state_event:Status

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

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

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

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

可能的重复: 如何在视图中启用Rails I18n转换错误?

接受的答案是:

 config.i18n.fallbacks = false 

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

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