I want to see not valid value in validation message.
validates_uniqueness_of :event, :scope => :user_id
Result: "Title has already has been taken" I want: "Event #{event} already has been taken by #{user}"
i'm trying do this way, bun not working:
validates_uniqueness_of :event, :scope => :user_id, :message=>"#{self.event} already has been taken by #{self.user}"
Use a lambda, but at least in more recent versions of Rails, ActiveRecord will try to pass in two parameters to that lambda, and it needs to account for them. Using a simpler example, let's say we want to ensure a username only contains alphanumeric characters:
validates_format_of :username, :with => /^[a-z0-9]+$/i,
:message => lambda{|x,y| "must be alphanumeric, but was #{y[:value]}"}
The first parameter passed to the lambda is an odd not-so-little symbol that would be great for telling a robot what went wrong:
:"activerecord.errors.models.user.attributes.username.invalid"
(In case you're confused by the notation above, symbols can contain more than just letters, numbers, and underscores. But if they do, you have to put quotes around them because otherwise :activerecord.errors
looks like you're trying to call the .errors
method on a symbol called :activerecord
.)
The second parameter contains a hash with the fields that will help you "pretty up" your error response. If I try to add a username with punctuation like "Superstar!!!", it will look something like this:
{
:model=>"User",
:attribute=>"Username",
:value=>"Superstar!!!"
}
From the ActiveRecord source code comment:
The values :model, :attribute and :value are always available for interpolation The value :count is available when applicable. Can be used for pluralization.
So you can simply write your message as
validates_uniqueness_of :event, :scope => :user_id,
:message=>"{{value}} is already taken"
Well, actually in Rails 3.x it is neither %{{value}} nor {{value}} but %{value}.
use a lambda :
validates_uniqueness_of :event, :scope => :user_id, :message=> lambda { |e| "#{e.event} already has been taken by #{e.user}"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With