Fix: PG::UniqueViolation (MAYBE-RAILS-CW) #1680
Open
+36
−1
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.
The error PG::UniqueViolation indicates that the application is attempting to create duplicate Transfer records with the same inflow_transaction_id and outflow_transaction_id pair. This violates the unique constraint defined in the database migration.
The root cause is in the auto_match_for_account method's LEFT JOIN condition. The current implementation uses OR logic which means it only excludes transfers where either the inflow OR outflow transaction matches, but not necessarily both. This can lead to situations where a transfer exists between two transactions, but the method still tries to create another transfer between the same pair.
Changes made:
Modified the LEFT JOIN condition in auto_match_for_account:
Added a new test "auto_match_for_account does not create duplicate transfers":
Added test "auto_match_for_account handles multiple potential matches":
The original intent of the code was to automatically match transfers between accounts by finding transactions with opposite amounts within a 4-day window. The changes preserve this functionality while properly handling the case where a transfer already exists between two transactions.
Tip
You can make revisions or ask questions of Revise.dev by using
/revise
in any comment or review!/revise Add a comment above the method to explain why we're making this change.
/revise Why did you choose to make this change specifically?
Important
If something doesn't look right, click to retry this interaction.