Rails override validation message

前端 未结 4 580
慢半拍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:49

    use a lambda :

    validates_uniqueness_of :event, :scope => :user_id, :message=> lambda { |e| "#{e.event} already has been taken by #{e.user}"}
    
    0 讨论(0)
  • 2020-12-13 22:54

    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"
    
    0 讨论(0)
  • 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!!!"
    }
    
    0 讨论(0)
  • 2020-12-13 23:00

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

    0 讨论(0)
提交回复
热议问题