validates_each

validates_each(*attr_names, &block)
Instance Public methods

Validates each attribute against a block.

class Person
  include ActiveModel::Validations

  attr_accessor :first_name, :last_name

  validates_each :first_name, :last_name, allow_blank: true do |record, attr, value|
    record.errors.add attr, 'starts with z.' if value.to_s[0] == ?z
  end
end

Options:

  • :on - Specifies the contexts where this validation is active. You can pass a symbol or an array of symbols. (e.g. on: :create or on: :custom_validation_context or on: [:create, :custom_validation_context])

  • :allow_nil - Skip validation if attribute is nil.

  • :allow_blank - Skip validation if attribute is blank.

  • :if - Specifies a method, proc or string to call to determine if the validation should occur (e.g. if: :allow_validation, or if: Proc.new { |user| user.signup_step > 2 }). The method, proc or string should return or evaluate to a true or false value.

  • :unless - Specifies a method, proc or string to call to determine if the validation should not occur (e.g. unless: :skip_validation, or unless: Proc.new { |user| user.signup_step <= 2 }). The method, proc or string should return or evaluate to a true or false value.

doc_ruby_on_rails
2015-06-20 00:00:00
Comments
Leave a Comment

Please login to continue.