Ensure promotion codes don't trigger ActiveRecord::RecordNotUnique errors on save #4228
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description
Promotion codes are always stored in the database in lowercase. Up to this PR, the transformation of the in-memory value of a code was performed in a
before_save
callback.This implementation led to a weird behavior that can easily be reproduced with a fresh Solidus install:
Screen.Recording.2021-12-24.at.13.02.24.mov
The expected error handling would be that any input that would end up matching an existing code (after having been stripped of spaces & downcased) should trigger the same flash error rather than crash the page.
This behavior can be achieved by normalizing values earlier in a
before_validation
callback: that way, the validation callback will query the database using a stripped/downcased value and, should a match be found, set an error on the model instance as expected.Checklist:
[ ] I have updated Guides and README accordingly to this change (if needed)