Reputation: 4389
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
Upvotes: 30
Views: 19201
Reputation: 545
What version of Rails do you use?
If Rails 3. then as i understand you should use :message => '%{value} has already been taken'
. I am not sure about Rails 2.3. - but in any case you can create your own custom validation that performs what you need.
Upvotes: 3
Reputation: 5477
2 things:
%{value}
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'
Upvotes: 46
Reputation: 124419
It looks like you can pass a Proc
to the message. When you do this, you get two parameters:
:activerecord.errors.models.user.attributes.name.taken
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."
}
Upvotes: 26