views:

5768

answers:

3

Using Rails I'm trying to get an error message like "The song field can't be empty" on save. Doing the following:

validates_presence_of :song_rep_xyz, :message => "can't be empty"

... only displays "Song Rep XYW can't be empty", which is not good because the title of the field is not user friendly. How can I change the title of the field itself ? I could change the actual name of the field in the database, but I have multiple "song" fields and I do need to have specific field names.

I don't want to hack around rails' validation process and I feel there should be a way of fixing that.

+12  A: 

Try this.

class User < ActiveRecord::Base
  validate do |user|
    user.errors.add_to_base("Country can't be blank") if user.country_iso.blank?
  end
end

I found this here.

Here is another way to do it. What you do is define a human_attribute_name method on the model class. The method is passed the column name as a string and returns the string to use in validation messages.

class User < ActiveRecord::Base

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

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

end

The above code is from here

Maulin
The problem is that my field is called :song_rep_xyz (well, something complicated), which is not user friendly
marcgg
I just edited the question to be clearer
marcgg
Nice, thanks for this!
Yar
+3  A: 

I recommend installing the custom_err_msg plugin which lets you do stuff like:

validates_presence_of :non_friendly_field_name, :message => "^Friendly field name is blank"
Ryan Bigg
thanks!isn't there a way to do it without a plugin ?
marcgg
+11  A: 

Now, the accepted way to set the humanized names is to use locales.

# config/locales/en.yml
en:
  activerecord:
    attributes:
      user:
        email: "E-mail address"
graywh