Last active
January 6, 2017 11:27
-
-
Save phansch/7097cf045cb4951df3ba4be4eaf88e1f to your computer and use it in GitHub Desktop.
Rails: Validating uniqueness without saving
This file contains 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
# Had to do this for an importer tool that was being converted to a three-step validation-feedback-persist process | |
# Rails does not support uniqueness validation for a custom collection of unsaved ActiveRecord models | |
# Maybe someone finds this useful | |
def validate_uniqueness | |
ActiveRecord::Base.transaction do | |
@unsaved_entities.each do |entity| | |
entity.object.save # Executes validations/callbacks | |
entity.successful = entity.object.valid? | |
end | |
# Roll back all changes | |
raise ActiveRecord::Rollback | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Had to do this for an importer tool that was being converted to a three-step validation-feedback-persist process.
Rails does not support uniqueness validation for a custom collection of unsaved ActiveRecord models.