Class: Reform::Form::UniqueValidator

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

Instance Method Summary collapse

Instance Method Details

#validate_each(form, attribute, value) ⇒ Object



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

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

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

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