Skip to content

Instantly share code, notes, and snippets.

@sankalpk
Created July 18, 2020 01:16
Show Gist options
  • Save sankalpk/8291e2abb4b8e92fb51c7b842e6a444a to your computer and use it in GitHub Desktop.
Save sankalpk/8291e2abb4b8e92fb51c7b842e6a444a to your computer and use it in GitHub Desktop.
class ArrayValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
array_elements_are_unique(record, attribute, value)
array_elements_are_subset_of_valid_list(record, attribute, value, options[:with])
field_is_present(record, attribute, value)
end
def array_elements_are_unique(record, attribute, value)
if value.present? && (value.uniq.size < value.size)
record.errors.add(attribute, 'are duplicated')
false
else
true
end
end
def array_elements_are_subset_of_valid_list(record, attribute, value, valid_list)
if (value & valid_list) == value
true
else
record.errors.add(attribute, 'are not valid')
end
end
def field_is_present(record, attribute, value)
if !value.nil? && value.try(:size) >= 0
true
else
record.errors.add(field_name, 'are missing')
false
end
end
end
class User
VALID_RACES = %w[black americanIndian asian pacificIslander white]
validates :races, array: { with: VALID_RACES }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment