2

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".

ClosureCowboy
  • 20,825
  • 13
  • 57
  • 71
  • By "humanized" do you mean "localized"? Or actually the humanize form via a method like http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-humanize – raidfive Jan 31 '11 at 01:39
  • @raidfive Thank you for the opportunity to clarify. I've updated the question. – ClosureCowboy Jan 31 '11 at 01:46
  • Related: https://stackoverflow.com/questions/4474028/ruby-on-rails-uncapitalize-first-letter – Jon Schneider Dec 01 '17 at 03:04

2 Answers2

3

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.

windstrewn
  • 51
  • 4
  • 1
    I've voted you up for bringing this question back to life, and for providing a solution that does result in lowercase letters being displayed. I've decided to go with the other answer, though. – ClosureCowboy Apr 29 '11 at 05:04
  • 3
    I'd argue that CSS is the wrong place to do this. This is a server issue so fix it on the server. – Tim Down Jul 22 '13 at 09:54
1

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
smathy
  • 26,283
  • 5
  • 48
  • 68