Ruby-on-rails – Fully custom validation error message with Rails

ruby-on-rails

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.

Best Answer

Now, the accepted way to set the humanized names and custom error messages is to use locales.

# config/locales/en.yml
en:
  activerecord:
    attributes:
      user:
        email: "E-mail address"
    errors:
      models:
        user:
          attributes:
            email:
              blank: "is required"

Now the humanized name and the presence validation message for the "email" attribute have been changed.

Validation messages can be set for a specific model+attribute, model, attribute, or globally.

Related Topic