Skip to content

Instantly share code, notes, and snippets.

@phansch
Last active January 6, 2017 11:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phansch/7097cf045cb4951df3ba4be4eaf88e1f to your computer and use it in GitHub Desktop.
Save phansch/7097cf045cb4951df3ba4be4eaf88e1f to your computer and use it in GitHub Desktop.
Rails: Validating uniqueness without saving
# 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
@phansch
Copy link
Author

phansch commented Jan 6, 2017

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment