Class: SetValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/hippo/validators/set.rb

Overview

A custom validator “set”. It’s similar to :presence validator Unlike :presence, :set doesn’t care whether the associated record is valid or not, just that it is present Also unlike :presence, it only works on belongs_to

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/hippo/validators/set.rb', line 6

def validate_each( record, attribute, value)
    association = record.class.reflect_on_association( attribute )

    if association.nil? || !association.belongs_to?
        raise ArgumentError, "Cannot validate existence on #{record.class} #{attribute}, not a :belongs_to association"
    end

    if record.send( attribute ).nil?
        record.errors.add( attribute, "is not set")
    end

end