Class: ApacheAge::Validators::UniqueNode

Inherits:
ActiveModel::Validator
  • Object
show all
Defined in:
lib/apache_age/validators/unique_node.rb

Instance Method Summary collapse

Instance Method Details

#validate(record) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/apache_age/validators/unique_node.rb', line 12

def validate(record)
  allowed_keys = record.age_properties.keys
  attributes = options[:attributes]
  return if attributes.blank?

  record_attribs =
    attributes
    .map { |attr| [attr, record.send(attr)] }
    .to_h.symbolize_keys
    .slice(*allowed_keys)
  query = record.class.find_by(record_attribs)

  # if no match is found or if it finds itself, it's valid
  return if query.blank?  || (query.id == record.id)

  record.errors.add(:base, 'record not unique')
  attributes.each { record.errors.add(_1, 'property combination not unique') }
end