Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails override validation message

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}"
like image 778
murato Avatar asked Nov 12 '10 18:11

murato


4 Answers

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!!!"
}
like image 27
Jaime Bellmyer Avatar answered Nov 19 '22 01:11

Jaime Bellmyer


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"
like image 183
Harish Shetty Avatar answered Nov 19 '22 00:11

Harish Shetty


Well, actually in Rails 3.x it is neither %{{value}} nor {{value}} but %{value}.

like image 44
Rollo Tomazzi Avatar answered Nov 19 '22 01:11

Rollo Tomazzi


use a lambda :

validates_uniqueness_of :event, :scope => :user_id, :message=> lambda { |e| "#{e.event} already has been taken by #{e.user}"}
like image 5
shingara Avatar answered Nov 19 '22 01:11

shingara