Rails validation error messages: Displaying only one error message per field

后端 未结 13 897
情话喂你
情话喂你 2020-12-07 17:08

Rails displays all validation error messages associated with a given field. If I have three validates_XXXXX_of :email, and I leave the field blank, I get three

13条回答
  •  佛祖请我去吃肉
    2020-12-07 17:50

    # Extracts at most one error message per field from the errors-object.
    # @param  [ActiveModel::Errors] the_errors_object The errors-object.
    # @raise  [ArgumentError] If the given argument is not an instance of ActiveModel::Errors.
    # @return [Array] A string-array containing at most one error message per field from the given errors-object.
    def get_one_error_per_field(the_errors_object)
      if the_errors_object.is_a? ActiveModel::Errors    
        errors = {}  
        the_errors_object.each do |field_name, associated_error|
          errors[field_name] = the_errors_object.full_message(field_name, associated_error) unless errors[field_name]
        end 
        return errors.values
      else
        raise ArgumentError.new('The given argument isn\'t an instance of ActiveModel::Errors!')
      end 
    end 
    

提交回复
热议问题