Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner 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
You can’t perform that action at this time.