Module: Perfectline::Validations::ValidatesExistence::ClassMethods

Defined in:
lib/validates_existence.rb

Instance Method Summary collapse

Instance Method Details

#validates_existence_of(*attr_names) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/validates_existence.rb', line 11

def validates_existence_of(*attr_names)
  configuration = {:message => "does not exist", :on => :save}
  configuration.update(attr_names.extract_options!.symbolize_keys)

  send(validation_method(configuration[:on] || :save), configuration) do |record|

    attr_names.each do |attr|
      attribute = attr.to_s.sub(/_id$/, '').to_sym
      association = reflect_on_association(attribute)

      if association.nil? || association.macro != :belongs_to
        raise ArgumentError, "Can not validate existence on #{attribute}, not a belongs_to association."
      end

      value = record.__send__(association.primary_key_name)
      next if value.nil? && configuration[:allow_nil]

      if association.options.has_key?(:foreign_type)
        foreign_type = record.__send__(association.options[:foreign_type])
        
        if not foreign_type.blank?
          association_class = foreign_type.constantize
        else
          record.errors.add(attr, configuration[:message]) and next
        end
      else
        association_class = association.klass
      end

      record.errors.add(attr, :existence, :default => configuration[:message]) unless association_class.exists?(value)
    end
  end
end