据我所知,在Rails3中设置字段的“人性化”名称的公认方法是使用locale:
# config/locales/en.yml
en:
activerecord:
attributes:
member:
username: 'username' # rather than 'Username'不过,我只是希望Rails3使用其默认人性化名称的小写版本。有没有一种简单的内置方法可以做到这一点?
下面是一个有助于澄清的示例:当在form_for中时,<%= f.label :username %>默认显示“用户名”。我想让它显示“用户名”。
发布于 2011-04-29 02:09:43
默认情况下,label帮助器使用human_attribute_name将属性转换为人名。如果你看一下源代码,在退回到attributes.to_s.humanize之前,human_attribute_name尝试了一些东西。它首先尝试转换,然后在选项散列中查找:default选项。
所以,获得你想要的功能的最简单/最好的方法是用你自己的重写human_attribute_name,它提供一个:default选项,然后调用原始的。Rails提供了一种使用alias_method_chain完成这类工作的合理方法,因此...
我听够了,快给我答案!
将以下内容放入config/initializers中的任意文件中,然后重新启动应用程序:
module ActiveModel
module Translation
def human_attribute_name_with_foo attribute, options = {}
human_attribute_name_without_foo attribute, options.merge( :default => attribute.humanize.downcase )
end
alias_method_chain :human_attribute_name, :foo
end
end发布于 2011-04-28 22:47:08
我也有同样的问题。我通过css解决了这个问题:
在foo.html.erb中:
<%= f.label :username, :class => "my_class" %>在bar.css中:
label.my_class {
text-transform: lowercase;
}我也更喜欢不同的解决方案。但到目前为止,这是我唯一能找到的。
https://stackoverflow.com/questions/4846841
复制相似问题