Created
January 3, 2020 03:08
-
-
Save justalever/73a1b36df8468ec101f54381996fb9d1 to your computer and use it in GitHub Desktop.
Validate an array data type in Ruby on Rails using a custom validator - PostGresQL allows arrays as a DB type.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Define the validator | |
# app/validators/array_validator.rb | |
class ArrayValidator < ActiveModel::EachValidator | |
def validate_each(record, attribute, values) | |
Array(values).each do |value| | |
options.each do |key, args| | |
validator_options = { attributes: attribute } | |
validator_options.merge!(args) if args.is_a?(Hash) | |
next if value.nil? && validator_options[:allow_nil] | |
next if value.blank? && validator_options[:allow_blank] | |
validator_class_name = "#{key.to_s.camelize}Validator" | |
validator_class = begin | |
validator_class_name.constantize | |
rescue NameError | |
"ActiveModel::Validations::#{validator_class_name}".constantize | |
end | |
validator = validator_class.new(validator_options) | |
validator.validate_each(record, attribute, value) | |
end | |
end | |
end | |
end | |
# include it in a model | |
class User | |
validates :tags, array: { presence: true, inclusion: { in: %w{ ruby rails } } | |
end |
Thanks for providing this validator.
It works perfectly fine except for a little fix in using this validator in the model.
validates :tags, presence: true, array: { inclusion: { in: %w(ruby rails) } }
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
how can I use rspec to test this code