As far as I know, the accepted way to set the "humanized" names of field开发者_如何学编程s 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".
I had the same problem. I solved it via css:
In foo.html.erb:
<%= f.label :username, :class => "my_class" %>
In bar.css:
label.my_class {
text-transform: lowercase;
}
I would prefer a different solution, too. But that's the only one I've been able to find, so far.
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 to attributes.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 with alias_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:
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
精彩评论