Module: ActiveRecord::Validations

Defined in:
lib/active_record/validations.rb

Overview

Active Records implement validation by overwriting Base#validate (or the variations, validate_on_create and validate_on_update). Each of these methods can inspect the state of the object, which usually means ensuring that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).

Example:

class Person < ActiveRecord::Base
  protected
    def validate
      errors.add_on_empty %w( first_name last_name )
      errors.add("phone_number", "has invalid format") unless phone_number =~ /[0-9]*/
    end

    def validate_on_create # is only run the first time a new object is saved
      unless valid_discount?(membership_discount)
        errors.add("membership_discount", "has expired")
      end
    end

    def validate_on_update
      errors.add_to_base("No changes have occured") if unchanged_attributes?
    end
end

person = Person.new("first_name" => "David", "phone_number" => "what?")
person.save                         # => false (and doesn't do the save)
person.errors.empty?                # => false
person.count                        # => 2
person.errors.on "last_name"        # => "can't be empty"
person.errors.on "phone_number"     # => "has invalid format"
person.each_full { |msg| puts msg } # => "Last name can't be empty\n" +
                                         "Phone number has invalid format"

person.attributes = { "last_name" => "Heinemeier", "phone_number" => "555-555" }
person.save # => true (and person is now saved in the database)

An Errors object is automatically created for every Active Record.

Please do have a look at ActiveRecord::Validations::ClassMethods for a higher level of validations.

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

VALIDATIONS =
%w( validate validate_on_create validate_on_update )

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.append_features(base) ⇒ Object

:nodoc:



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/active_record/validations.rb', line 44

def self.append_features(base) # :nodoc:
  super

  base.class_eval do
    alias_method :save_without_validation, :save
    alias_method :save, :save_with_validation

    alias_method :update_attribute_without_validation_skipping, :update_attribute
    alias_method :update_attribute, :update_attribute_with_validation_skipping

    VALIDATIONS.each { |vd| base.class_eval("def self.#{vd}(*methods) write_inheritable_array(\"#{vd}\", methods - (read_inheritable_attribute(\"#{vd}\") || [])) end") }
  end
  
  base.extend(ClassMethods)
end

Instance Method Details

#errorsObject

Returns the Errors object that holds all information about attribute error messages.



352
353
354
355
# File 'lib/active_record/validations.rb', line 352

def errors
  @errors = Errors.new(self) if @errors.nil?
  @errors
end

#save_with_validation(perform_validation = true) ⇒ Object

The validation process on save can be skipped by passing false. The regular Base#save method is replaced with this when the validations module is mixed in, which it is by default.



321
322
323
# File 'lib/active_record/validations.rb', line 321

def save_with_validation(perform_validation = true)
  if perform_validation && valid? || !perform_validation then save_without_validation else false end
end

#update_attribute_with_validation_skipping(name, value) ⇒ Object

Updates a single attribute and saves the record without going through the normal validation procedure. This is especially useful for boolean flags on existing records. The regular update_attribute method in Base is replaced with this when the validations module is mixed in, which it is by default.



328
329
330
331
# File 'lib/active_record/validations.rb', line 328

def update_attribute_with_validation_skipping(name, value)
  self[name] = value
  save(false)
end

#valid?Boolean

Runs validate and validate_on_create or validate_on_update and returns true if no errors were added otherwise false.

Returns:

  • (Boolean)


334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'lib/active_record/validations.rb', line 334

def valid?
  errors.clear

  run_validations(:validate)
  validate

  if new_record?
    run_validations(:validate_on_create)
    validate_on_create 
  else
    run_validations(:validate_on_update)
    validate_on_update
  end

  errors.empty?
end