Class: Perfectline::ValidatesExistence::Rails3::ExistenceValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/rails3.rb

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ ExistenceValidator

Returns a new instance of ExistenceValidator.



12
13
14
15
16
17
# File 'lib/rails3.rb', line 12

def initialize(options)
  # set the default message if its unspecified
  options[:message] ||= :existence
  options[:both]    = true unless options.key?(:both)
  super(options)
end

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object



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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/rails3.rb', line 19

def validate_each(record, attribute, value)
  normalized = attribute.to_s.sub(/_id$/, "").to_sym
  association = record.class.reflect_on_association(normalized)

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

  target_class = nil

  # dealing with polymorphic belongs_to
  if association.options[:polymorphic]
    foreign_type = record.send(association.options[:foreign_type] || association.foreign_type)
    target_class = foreign_type.constantize unless foreign_type.nil?
  else
    target_class = association.klass
  end

  if value.nil? || target_class.nil? || !target_class.exists?(value)
    errors = [attribute]

    # add the error on both :relation and :relation_id
    if options[:both]
      if Rails::VERSION::MINOR >= 1
        foreign_key = association.foreign_key
      else
        foreign_key = association.primary_key_name
      end

      errors << (attribute.to_s.ends_with?("_id") ? normalized : foreign_key)
    end

    messages = [:"#{record.class.i18n_scope}.errors.messages.existence", "does not exist"]

    errors.each do |error|
      record.errors.add(error, options[:message], :message => messages)
    end
  end
end