Custom Humanize Column Names in Ruby on Rails

Henrik, from The Pug Automatic, suggested a great way of having custom column names on the rails validation error messages, by rewriting the human_attribute_name of ActiveRecord. There’s an example on his blog (really worth a look and not only for this specific post) on how to do that. Beware that it uses a deprecated method of ActiveRecord, that may be removed in future versions of Rails (it is still there on Rails 2.0). The workaround is discussed there too on the comments: One could rewrite the humanize method of String – that would make changes global – or we can just ask politely for the core developers not to remove the method :).

Here is an example of how to do that, I used it on an application of mine. On this case, the collumns on the database are in english, which I prefer working with when programming , but the users can barely read Portuguese, so I need to translate to them:

class Ticket < ActiveRecord::Base
  HUMANIZED_ATTRIBUTES = {
    :description => "Descrição",
    :category => "Categoria",
    :title => "Assunto"
  }

  def self.human_attribute_name(attr)
    HUMANIZED_ATTRIBUTES(attr.to_sym) || super
  end
end
About these ads

~ by Dante Regis on December 10, 2007.

3 Responses to “Custom Humanize Column Names in Ruby on Rails”

  1. Shouldn’t “supper” have only one p?

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

  2. Hi Guilherme, that’s correct, my mistake. I’m fixing it right now! Thanks.

  3. Hi, I think you need square brackets here: HUMANIZED_ATTRIBUTES[attr.to_sym]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

%d bloggers like this: