Flowdock

Active Record classes can implement validations in several ways. The highest level, easiest to read, and recommended approach is to use the declarative validates_..._of class methods (and validates_associated) documented below. These are sufficient for most model validations.

Slightly lower level is validates_each. It provides some of the same options as the purely declarative validation methods, but like all the lower-level approaches it requires manually adding to the errors collection when the record is invalid.

At a yet lower level, a model can use the class methods validate, validate_on_create and validate_on_update to add validation methods or blocks. These are ActiveSupport::Callbacks and follow the same rules of inheritance and chaining.

The lowest level style is to define the instance methods validate, validate_on_create and validate_on_update as documented in ActiveRecord::Validations.

validate, validate_on_create and validate_on_update Class Methods

Calls to these methods add a validation method or block to the class. Again, this approach is recommended only when the higher-level methods documented below (validates_..._of and validates_associated) are insufficient to handle the required validation.

This can be done with a symbol pointing to a method:

  class Comment < ActiveRecord::Base
    validate :must_be_friends

    def must_be_friends
      errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
    end
  end

Or with a block which is passed the current record to be validated:

  class Comment < ActiveRecord::Base
    validate do |comment|
      comment.must_be_friends
    end

    def must_be_friends
      errors.add_to_base("Must be friends to leave a comment") unless commenter.friend_of?(commentee)
    end
  end

This usage applies to validate_on_create and validate_on_update as well.

Constants

DEFAULT_VALIDATION_OPTIONS = { :on => :save, :allow_nil => false, :allow_blank => false, :message => nil

ALL_RANGE_OPTIONS = [ :is, :within, :in, :minimum, :maximum ].freeze

ALL_NUMERICALITY_CHECKS = { :greater_than => '>', :greater_than_or_equal_to => '>=', :equal_to => '==', :less_than => '<', :less_than_or_equal_to => '<=', :odd => 'odd?', :even => 'even?' }.freeze

Attributes

Show files where this module is defined (1 file)
Register or log in to add new notes.
June 12, 2009
1 thank

Conditions work for lower-level validate methods too

I don’t think this is mentioned in the docs anywhere, or else I couldn’t find it: Because validate, validate_on_create, and validate_on_update are ActiveSupport::Callbacks, their symbol forms support conditions just like validates_presence_of and company:

validate :permaname_must_be_unique, :if => :normal_entry?
validate_on_create :posted_at_must_be_valid_timestamp, :unless => Proc.new {|e| e.posted_at.nil? }
validate_on_update :title_must_not_contain_apostrophes, :if => :title_starts_with_a_b?