Skip to content

Instantly share code, notes, and snippets.

@bbugh
Last active April 30, 2024 06:20
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bbugh/fadf8c65b7f4d3eaa55e64acfc563ab2 to your computer and use it in GitHub Desktop.
Save bbugh/fadf8c65b7f4d3eaa55e64acfc563ab2 to your computer and use it in GitHub Desktop.
Rails Postgres Array Column Validator
# app/models/validators/array_inclusion_validator.rb
class ArrayInclusionValidator < ActiveModel::EachValidator
include ActiveModel::Validations::Clusivity
def validate_each(record, attribute, values)
values.each do |value|
unless include?(record, value)
message = (options[:message].try(:gsub, '%{value}', value) || "#{value} is not included in the list")
record.errors.add(attribute, :array_inclusion, message: message, value: value)
end
end
end
end
# app/models/model.rb
class DemoModel < ApplicationRecord
BULB_THINGS = %w[A19 B52 C3P0]
validates :things, array_inclusion: { in: BULB_THINGS }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment