Class: BelongsToValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/validates-belongs-to.rb

Overview

Validation to ensure that two ActiveModel associations are related to each other.

class JobApplication
  belongs_to :resume
  belongs_to :user
  validates :resume, :belongs_to => :user
end

Instance Method Summary collapse

Instance Method Details

#check_validity!Object



11
12
13
14
15
# File 'lib/validates-belongs-to.rb', line 11

def check_validity!
  unless options[:with]
    raise ArgumentError, "An association must be specified."
  end
end

#validate_each(record, attribute, value) ⇒ Object



16
17
18
19
20
21
22
23
24
# File 'lib/validates-belongs-to.rb', line 16

def validate_each(record, attribute, value)
  if value
    if common_owner = record.send(options[:with])
      unless common_owner == value.send(options[:with])
        record.errors.add(attribute, :belongs_to, options.merge(:value => value))
      end
    end
  end
end