Files
openfoodnetwork/app/validators/vouchers/scoped_uniqueness_validator.rb
Gaetan Craig-Riou 73819a4638 Fix unique validator for vouche code
Paranoia doesn't support unique validation including deleted records:
  https://github.com/rubysherpas/paranoia/pull/333
We use a custom validator, ScopedUniquenessValidator to avoid the issue
2024-11-28 13:35:01 +01:00

26 lines
755 B
Ruby

# frozen_string_literal: false
# paranoia doesn't support unique validation including deleted records:
# https://github.com/rubysherpas/paranoia/pull/333
# We use a custom validator to fix the issue, so we don't need to fork/patch the gem
module Vouchers
class ScopedUniquenessValidator < ActiveModel::Validator
def validate(record)
@record = record
return unless unique_voucher_code_per_enterprise?
record.errors.add :code, :taken, value: @record.code
end
private
def unique_voucher_code_per_enterprise?
query = Voucher.with_deleted.where(code: @record.code, enterprise_id: @record.enterprise_id)
query = query.where.not(id: @record.id) unless @record.id.nil?
query.present?
end
end
end