Class: ActiveModel::Validations::WriteOnceValidator

Inherits:
EachValidator
  • Object
show all
Defined in:
lib/can_has_validations/validators/write_once_validator.rb

Instance Method Summary collapse

Instance Method Details

#validate(record) ⇒ Object

as of ActiveModel 4, allow_nil: true causes a change from a value back to

nil to be allowed. prevent this.


13
14
15
16
17
# File 'lib/can_has_validations/validators/write_once_validator.rb', line 13

def validate(record)
  attributes.each do |attribute|
    validate_each(record, attribute, nil)
  end
end

#validate_each(record, attribute, _) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/can_has_validations/validators/write_once_validator.rb', line 19

def validate_each(record, attribute, _)
  return unless record.persisted?
  if ( !record.respond_to?("#{attribute}_changed?") ||
       !record.respond_to?("#{attribute}_was")
     ) && record.respond_to?("#{attribute}_id_changed?")
    attr2 = "#{attribute}_id"
  else
    attr2 = attribute
  end
  if record.send("#{attr2}_changed?")
    if options[:immutable_nil] || !record.send("#{attr2}_was").nil?
      value = record.read_attribute_for_validation(attribute)
      record.errors.add(attribute, :unchangeable, **options.except(:immutable_nil).merge!(value: value))
    end
  end
end