Class: Reform::Form::UniqueValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/reform/form/validation/unique_validator.rb

Overview

Reform’s own implementation for uniqueness which does not write to model.

Instance Method Summary collapse

Instance Method Details

#validate_each(form, attribute, value) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
# File 'lib/reform/form/validation/unique_validator.rb', line 3

def validate_each(form, attribute, value)
  model = form.model_for_property(attribute)

  # search for models with attribute equals to form field value
  query = model.class.where(attribute => value)

  # if model persisted, excluded own model from query
  query = query.merge(model.class.where("id <> ?", model.id)) if model.persisted?

  # if any models found, add error on attribute
  form.errors.add(attribute, "#{attribute} must be unique.") if query.any?
end