module ClassMethods

Ruby on Rails 2.3.18

Since v2.2.3

Available in: v2.2.3 v2.3.18 v3.0.20 v3.1.12 v3.2.22.5 v4.0.13 v4.1.16 v4.2.9 v5.2.8.1 v6.0.6 v6.1.7.10 v7.0.10 v7.1.6 v7.2.3 v8.0.4 v8.1.2

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

Methods (defined here)

Private methods

(1) Implementation detail — not part of the public API.

Used by

Extendd by (1)

Type at least 2 characters to search.

↑↓ navigate · open · esc close