randombits
randombits

Reputation: 48450

Ruby on Rails: controlling the layout of an error message in ActiveRecord

My error messages in Rails look like the following:

"Email Your email is invalid."

Why is the name of the field prefixed within the string itself? It makes the error messages look awfully odd.

Is there anyway to circumvent this behavior so that I can just see "Your email is invalid."

Upvotes: 1

Views: 928

Answers (1)

Robert Speicher
Robert Speicher

Reputation: 15552

The documentation for generate_full_message might be of use:

The default full_message format for any locale is "{{attribute}} {{message}}". One can specify locale specific default full_message format by storing it as a translation for the key: "activerecord.errors.full_messages.format".

Additionally one can specify a validation specific error message format by storing a translation for: "activerecord.errors.full_messages.[message_key]". E.g. the full_message format for any validation that uses :blank as a message key (such as validates_presence_of) can be stored to: "activerecord.errors.full_messages.blank".

Because the message key used by a validation can be overwritten on the validates_* class macro level one can customize the full_message format for any particular validation:

# app/models/article.rb
class Article < ActiveRecord::Base
  validates_presence_of :title, :message => :"title.blank"
end

# config/locales/en.yml
en:
  activerecord:
    errors:
      full_messages:
        title:
          blank: This title is screwed!

In your case, since you're using the default {{attribute}} {{message}} format, you're getting "Email" for the attribute and "Your email is invalid" as the message. You could change the :message argument to "is not a valid format" and you should get "Email is not a valid format". That's the quick fix. If you want to fully customize it you can use the locale method above.

Upvotes: 4

Related Questions