Class: ActiveModel::Validations::OwnershipValidator

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

Instance Method Summary collapse

Instance Method Details

#check_validity!Object

Raises:

  • (ArgumentError)


18
19
20
21
# File 'lib/validators/validates_ownership_of.rb', line 18

def check_validity!
  raise ArgumentError, ":with is required" unless options.key?(:with)
  raise ArgumentError, ":with option must be a string or a symbol" unless ["String", "Symbol"].include?(options[:with].class.name)
end

#validate_each(record, attribute, value) ⇒ Object



4
5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/validators/validates_ownership_of.rb', line 4

def validate_each(record, attribute, value)
  owner = record.send(options[:with])
  actual_owner = value ? value.send(options[:with]) : nil

  return unless value
  return if owner == actual_owner

  record.errors.add(
    attribute,
    :invalid_owner,
    message: options[:message]
  )
end