how to customize rails activerecord validation error message to show attribute value

Spread the love

Question Description

When a user tries to create a record with a name that already exists, I want to show an error message like:

name "some name" has already been taken

I have been trying to do:

validates_uniqueness_of :name, :message => "#{name} has already been taken"

but this outputs the table name instead of the value of the name attribute

Practice As Follows

2 things:

  1. The validation messages use the Rails I18n style interpolation, which is %{value}
  2. The key is value rather than name, because in the context of internationalization, you don’t really care about the rest of the model.

So your code should be:

validates_uniqueness_of :name, :message => '%{value} has already been taken'

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.