Last active
April 30, 2024 06:20
-
-
Save bbugh/fadf8c65b7f4d3eaa55e64acfc563ab2 to your computer and use it in GitHub Desktop.
Rails Postgres Array Column Validator
This file contains hidden or 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
# 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 |
This file contains hidden or 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
# 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