Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 909
umar Avatar asked May 20 '11 14:05

umar


2 Answers

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' 
like image 193
Austin Taylor Avatar answered Oct 06 '22 12:10

Austin Taylor


It looks like you can pass a Proc to the message. When you do this, you get two parameters:

  1. A symbol along the lines of :activerecord.errors.models.user.attributes.name.taken
  2. A hash that looks something like `{:model=>"User", :attribute=>"Name", :value=>"My Name"}

So if you allow for two parameters on a proc, you can use the attributes[:value] item to get the name that was used:

validates_uniqueness_of :name,                          :message => Proc.new { |error, attributes|                            "#{attributes[:value]} has already been taken."                          } 
like image 45
Dylan Markow Avatar answered Oct 06 '22 14:10

Dylan Markow