Rails: Model.human_attribute_name :field should raise an error when translation not found? (Maybe caused by state_machine?)

早过忘川 提交于 2019-12-06 10:37:05

The problem lies in the fact that human_attribute_name falls back to

defaults << attribute.to_s.humanize

when nothing else found. In other words, human_attribute_name will never raise an error.

I "fixed" this by overriding human_attribute_name, patching the above mentioned line:

(put this in an initializer)

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
MrYoshiji

Possible duplicate of : How to enable Rails I18n translation errors in views?

The accepted answer is:

config.i18n.fallbacks = false

@BettySt 's answer is pretty cool too, you should take a look at her solution.

Doc about how to handle I18n translation errors: http://guides.rubyonrails.org/i18n.html#using-different-exception-handlers

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