Search

Friends

Atomspheric CO2 (PPM)

Archives

Blather

Uptime verified by Wormly.com

13 May 2008

Changing human attribute labels in Rails validation messages

I've been frustrated by the lack of humanity in Rails so-called human names. So I wrote a little library, which was largely stolen from Change displayed column name in Rails validation messages. The library lets you do something a little like this...

require 'human_attributes'

class Puppy < ActiveRecord::Base
  humanize_attributes :breakfast => "Puppy's preferred breakfast"
  validates_presence_of :breakfast
end

It doesn't do anything very spectacular, but it took me a long time to work out.

# lib/human_attributes.rb

module ActiveRecord
  class Base
    # Humanize attributes
    def self.human_attribute_name(attr)
      @humanized_attributes ||= {}
      @humanized_attributes[attr.to_sym] || attr.humanize
    end

    def self.humanize_attributes(*args)
      @humanized_attributes = *args
    end
  end
end

ActiveRecord::Base#human_attribute_name is deprecated and will be replaced by proper string inflection. For those with fancy, modern humanizing Inflectors you might have to change it to something like this.

def self.humanize_attributes(*args)
  humanized_attributes = *args
  Inflector.inflections do |inflect|
    humanized_attributes.each do |attr, label|
      inflect.human attr.to_s, label
    end
  end
end

Although I couldn't get that to work, probably because my Rails isn't new enough.

Comments

  1. […] Changing human attribute labels in Rails validation messages 中介绍的方法来本地化 ActiveRecord […]

    Rails I18N: ActiveRecord Model Human Name Made Easy @ 知易行难 / 11:36pm / 24 November 2008

  2. Now with Rails 2.2’s I18N, we could do this in a more elegant way. Apps of old Rails version do still need this though. So I bundle your code to a plugin, hosted at github: http://github.com/ashchan/humanize_attributes/tree/master

    James Chan / 11:43pm / 24 November 2008

  3. I’m glad you found it useful. I never got elite enough to start writing plugins.

    Ryan / 8:23am / 25 November 2008

  4. found useful

    test / 6:21pm / 6 February 2012

Leave a comment

Markdown

0.083 seconds