强行“人性化” Rails 3 中字段名称要小写
据我所知,在 Rails 3 中设置字段的“人性化”名称的公认方法是使用语言环境:
# config/locales/en.yml
en:
activerecord:
attributes:
member:
username: 'username' # rather than 'Username'
但是,我只是希望 Rails 3 使用其默认人性化名称的小写版本。有没有一种简单的内置方法可以做到这一点?
一个有助于澄清的示例:在 form_for
内部时,<%= f.label :username %>
默认显示“用户名”。我希望它显示“用户名”。
As far as I know, the accepted way to set the "humanized" names of fields in Rails 3 is to use locales:
# config/locales/en.yml
en:
activerecord:
attributes:
member:
username: 'username' # rather than 'Username'
However, I simply want Rails 3 to use lowercase versions of its default humanized names. Is there an easy, built-in way to do this?
An example to help clarify: When inside of a form_for
, <%= f.label :username %>
displays "Username" by default. I want it to display "username".
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我也有同样的问题。
我通过 css 解决了它:
In foo.html.erb:
In bar.css:
我也更喜欢不同的解决方案。但到目前为止,这是我唯一能找到的。
I had the same problem.
I solved it via css:
In foo.html.erb:
In bar.css:
I would prefer a different solution, too. But that's the only one I've been able to find, so far.
label
帮助器默认使用 human_attribute_name< /a> 将属性转换为人名。如果您查看源代码,human_attribute_name 会尝试一些操作,然后再返回到
attributes.to_s. humanize 。它首先尝试翻译,然后在选项哈希中查找
:default
选项。因此,获得所需功能的最简单/最好的方法是用您自己的提供
:default
选项覆盖human_attribute_name ,然后调用原始选项。 Rails 提供了一种合理的方法来使用
alias_method_chain
完成此类操作,所以...我已经听够了,只需给我答案即可!
将以下内容放入
config/initializers
中的任意文件中,然后重新启动您的应用:The
label
helper defaults to using human_attribute_name to turn an attribute into a human name. If you look at the source,human_attribute_name
tries a few things before falling back toattributes.to_s.humanize
. It tries the translation first, and then it looks for a:default
option in the options hash.So, the simplest/best way to get the functionality you want is to override
human_attribute_name
with your own that provides a:default
option and then calls the original. Rails provides a reasonable way to do this sort of thing withalias_method_chain
, so...I've heard enough, just give me the answer!
Put the following in any file in
config/initializers
and restart your app: