Add exactly_one_of validator for ActiveRecord models
Follow-up from !198202 (comment 2659472924)
We do use a validation like this in multiple places, so it would be great if we can have a validator for this and reuse everywhere.
Implementation plan
Something like this could work, but definitively open to any changes in the snippet below
class OnlyOnePresentValidator < ActiveModel::Validator
def validate(record)
fields = options[:fields]
values = fields.map { |field| record.public_send(field) }.compact
unless values.one?
record.errors.add(:base, "Exactly one of #{fields.join(', ')} must be present")
end
end
end
validates_with OnlyOnePresentValidator, fields: [:project_id, :group_id, :organization_id]
Support contact: @mcelicalderonG
Edited by 🤖 GitLab Bot 🤖