Class: ActiveModel::Validations::PreventBlankificationValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/active_model/validations/prevent_blankification_validator.rb

Overview

This validator prevents fields that were previously set to be blanked. Thus, we can allow blank fields, but once a field is set the value cannot be deleted again.

The record#attribute must have dirty tracking enabled. With Mongoid all Documents get that by default.

Usage: validates :field, prevent_blankification: true

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



15
16
17
18
19
20
21
22
23
# File 'lib/active_model/validations/prevent_blankification_validator.rb', line 15

def validate_each(record, attribute, value)
  must_have_dirty_tracking_enabled!(record, attribute)

  dirty_value = record.send "#{attribute}_was"

  if value.blank? && dirty_value.present?
    record.errors.add(attribute, :cannot_be_blanked)
  end
end