how to customize rails activerecord validation error message to show attribute value

后端 未结 3 916
甜味超标
甜味超标 2020-12-08 20:08

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

相关标签:
3条回答
  • 2020-12-08 20:17

    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.

    0 讨论(0)
  • 2020-12-08 20:27

    It looks like you can pass a Proc to the message. When you do this, you get two parameters:

    1. A symbol along the lines of :activerecord.errors.models.user.attributes.name.taken
    2. A hash that looks something like `{:model=>"User", :attribute=>"Name", :value=>"My Name"}

    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." 
                            }
    
    0 讨论(0)
  • 2020-12-08 20:36

    2 things:

    1. The validation messages use the Rails I18n style interpolation, which is %{value}
    2. The key is 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'
    
    0 讨论(0)
提交回复
热议问题