Skip to content

Instantly share code, notes, and snippets.

@vmcilwain
Created January 23, 2020 19:48
Show Gist options
  • Save vmcilwain/fe29c12b14fad034e9c50a9275ff7050 to your computer and use it in GitHub Desktop.
Save vmcilwain/fe29c12b14fad034e9c50a9275ff7050 to your computer and use it in GitHub Desktop.
Custom validator to allow creation of a record with duplicate content if it has been flagged as deleted.
# Custom validator to allow for duplicate content on an attribute in a class using acts_as_paranoid gem.
#
# Scenario:
# A user can create a record with an attribute with given content 'test'
# if a previous record with that attribute/content does not exist or if it does exist but was flagged as deleted (deleted_at IS NOT NULL)
#
# Usage:
# validates :attribute, paranoid_uniqueness: true
# or
# validates :attribute, paranoid_uniqueness: { scope: platform_id, message: 'custom message }
# Note scope and message is optional (obviously), If it needs to work with additional options, it will need to be built as required.
class ParanoidUniquenessValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
scope = options[:scope]
query = { attribute => record[attribute], deleted_at: nil }
query.merge!(scope => record[scope]) if scope
if record.class.with_deleted.where(query).any?
record.errors.add attribute, (options[:message] || 'has already been taken')
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment