Class: NonNilValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
app/validators/non_nil_validator.rb

Overview

Validates that an attribute’s value is not nil, but does allow blank, so is an alternative to ‘validate :attribute, presence: true` when empty should be allowed, but not nil.

Examples:

Validation declaration

validates :attribute,
          non_nil: true

Instance Method Summary collapse

Instance Method Details

#validate_each(model, attribute, value) ⇒ void

This method returns an undefined value.

Validates value is not nil. If value is nil, then the :nil error message is added to attribute on model.



15
16
17
18
19
# File 'app/validators/non_nil_validator.rb', line 15

def validate_each(model, attribute, value)
  if value.nil?
    model.errors.add(attribute, :nil)
  end
end