11

Possible Duplicate:
Custom model attribute (column name) title in Ruby on Rails

I've been using this solution in Rails 2.x forever:

   HUMANIZED_ATTRIBUTES = {
    :email => "E-mail address"
  }

  def self.human_attribute_name(attr)
    HUMANIZED_ATTRIBUTES[attr.to_sym] || super
  end

but this causes bizarre errors when getting the errors from an ActiveRecord instance. What is the correct way to get nice, human-readable names in Rails 3.x?

Community
  • 1
  • 1
Dan Rosenstark
  • 68,471
  • 58
  • 283
  • 421

2 Answers2

29

Using human_attribute_name with the I18n framework is more simple I think :

In your view : User.human_attribute_name("email")

In your locale yml file :

en:
  activerecord:
    attributes:
      user:
        email: E-mail address
tal
  • 3,423
  • 1
  • 25
  • 21
7

I think the correct Rails 3 approach would be to use the translation api, but I'm using human_attribute_name as follows:

def self.human_attribute_name(attr, options = {})
  HUMANIZED_ATTRIBUTES[attr.to_sym] || super
end

The call to super may be expecting the options argument to be there.

Brian Deterling
  • 13,556
  • 4
  • 55
  • 59
  • Cool that worked. I should've checked the API. Just FYI I'm using ` HUMANIZED_ATTRIBUTES[attr.to_sym] || super.split(" ").collect {|word| word.capitalize}.join(" ")` which is cute but trivial :) – Dan Rosenstark Jan 24 '11 at 22:31
  • 2
    Unless I'm misinterpreting what you're doing, I think super.titleize would do the same thing, that is, capitalize all the words. "foo bar baz".titleize => "Foo Bar Baz" – Brian Deterling Jan 24 '11 at 22:59
  • +1. There's some reason I don't use titlelize, like that it's Rails-only and not usable in Ruby. But in this case, it's perfect. – Dan Rosenstark Jan 24 '11 at 23:53
  • FYI `titlize` has other side-effects like removing dashes and other "non title" characters – bloudermilk Oct 17 '12 at 23:17