Module: ActiveRecord::Validations

Defined in:
lib/gems/activerecord-2.2.2/lib/active_record/validations.rb

Overview

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

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 occurred") 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.errors.count                 # => 2
person.errors.on "last_name"        # => "can't be empty"
person.errors.on "phone_number"     # => "has invalid format"
person.errors.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.

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

.included(base) ⇒ Object

:nodoc:



305
306
307
308
309
310
311
312
313
314
# File 'lib/gems/activerecord-2.2.2/lib/active_record/validations.rb', line 305

def self.included(base) # :nodoc:
  base.extend ClassMethods
  base.class_eval do
    alias_method_chain :save, :validation
    alias_method_chain :save!, :validation
  end

  base.send :include, ActiveSupport::Callbacks
  base.define_callbacks *VALIDATIONS
end

Instance Method Details

#errorsObject

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



1044
1045
1046
# File 'lib/gems/activerecord-2.2.2/lib/active_record/validations.rb', line 1044

def errors
  @errors ||= Errors.new(self)
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.



1007
1008
1009
1010
1011
1012
1013
# File 'lib/gems/activerecord-2.2.2/lib/active_record/validations.rb', line 1007

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

#save_with_validation!Object

Attempts to save the record just like Base#save but will raise a RecordInvalid exception instead of returning false if the record is not valid.



1017
1018
1019
1020
1021
1022
1023
# File 'lib/gems/activerecord-2.2.2/lib/active_record/validations.rb', line 1017

def save_with_validation!
  if valid?
    save_without_validation!
  else
    raise RecordInvalid.new(self)
  end
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)


1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
# File 'lib/gems/activerecord-2.2.2/lib/active_record/validations.rb', line 1026

def valid?
  errors.clear

  run_callbacks(:validate)
  validate

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

  errors.empty?
end