Rails override validation message

前端 未结 4 585
慢半拍i
慢半拍i 2020-12-13 22:15

I want to see not valid value in validation message.

validates_uniqueness_of :event, :scope => :user_id

Result: \"Title has already has

4条回答
  •  粉色の甜心
    2020-12-13 22:55

    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!!!"
    }
    

提交回复
热议问题