谢谢您的建议! @Arup Rakshit,你的建议向我指出ActiveModel::Translation#human_attribute_name
,这竟然是Rails的4
这里做到这一点的方式是我所做的:
的Gemfile:
gem 'titleize'
config/initializers/human_attribute_name.rb:
# Overrides human_attribute_name so model attributes are title case.
# Combine with the titleize gem which overrides String#titleize with English-language rules.
module ActiveModel::Translation
def human_attribute_name(attribute, options = {})
options = { count: 1 }.merge!(options)
parts = attribute.to_s.split(".")
attribute = parts.pop
namespace = parts.join("/") unless parts.empty?
attributes_scope = "#{self.i18n_scope}.attributes"
if namespace
defaults = lookup_ancestors.map do |klass|
:"#{attributes_scope}.#{klass.model_name.i18n_key}/#{namespace}.#{attribute}"
end
defaults << :"#{attributes_scope}.#{namespace}.#{attribute}"
else
defaults = lookup_ancestors.map do |klass|
:"#{attributes_scope}.#{klass.model_name.i18n_key}.#{attribute}"
end
end
defaults << :"attributes.#{attribute}"
defaults << options.delete(:default) if options[:default]
defaults << attribute.titleize
options[:default] = defaults
I18n.translate(defaults.shift, options)
end
end
# If you're using Rails enums and the enum_help gem to make them translatable, use this code to default to titleize instead of humanize
module EnumHelp::Helper
def self.translate_enum_label(klass, attr_name, enum_label)
::I18n.t("enums.#{klass.to_s.underscore.gsub('/', '.')}.#{attr_name}.#{enum_label}", default: enum_label.titleize)
end
end
如果你不使用枚举和enum_help,删除最后一位。
一个问题也可以发挥作用,但在我的项目中,没有理由不将它应用于每个模型。
美丽!
这可能是有用的:http://stackoverflow.com/questions/2842444/ruby-on-rails-converting-somewordhere-to-some-word-here – apod
['包括HumanAttributeOverride'](https: //gist.github.com/aruprakshit/113ee1e08d8f6efee2ddbbd2644e0463)在每个模型? 'HumanAttributeOverride'是一个关注模块。 –
如果你有足够小的单词数量不会被大写,并且你知道这个集合,那么就像这样做:http://stackoverflow.com/questions/14251311/capitalizing-titles – unflores