Skip to content

Instantly share code, notes, and snippets.

@skplunkerin
Last active December 6, 2023 05:02
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save skplunkerin/e778bf8463e9da7390c4 to your computer and use it in GitHub Desktop.
Save skplunkerin/e778bf8463e9da7390c4 to your computer and use it in GitHub Desktop.
rails custom error message validation without column

Best solution:

http://stackoverflow.com/a/808776/1180523

# model
validates   :email,    :uniqueness => { message: "is wrong" }
validates   :name,    :uniqueness => { message: "Your name is wrong" }

HUMANIZED_ATTRIBUTES = {
  :email => "E-mail address",
  :name => "" # don't include column name in error
}

def self.human_attribute_name(attr, options={})
  HUMANIZED_ATTRIBUTES[attr.to_sym] || super
end

# now the errors will be:
"E-mail address is wrong"
"Your name is wrong"

# instead of:
"Email E-mail address is wrong"
"Name Your name is wrong"

Double edged sword solution:

(because all errors will no longer have column name, forcing you to add customer error message for everything)

http://stackoverflow.com/a/20341297/1180523

# model
validates   :column_name,    :uniqueness => { message: "You're doing it wrong, bub" }

# config/locales/en.yml
en:
  errors:
    format: "#{message}"


# now the error will be:
"You're doing it wrong, bub"

# instead of:
"Column name You're doing it wrong, bub"
@asad-shakil
Copy link

This was very useful for me. Thanks for sharing.

@ibrahima
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment