Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Fix(exchange_rate): Handle RecordInvalid in find_or_fetch_rate race condition (#2734)

sentry[bot]32eef8e2eaec
diff --git a/app/models/exchange_rate/provided.rb b/app/models/exchange_rate/provided.rb
index e396cfe691..0d96038daf 100644
--- a/app/models/exchange_rate/provided.rb
+++ b/app/models/exchange_rate/provided.rb
@@ -41,10 +41,12 @@ module ExchangeRate::Provided
) do |exchange_rate|
exchange_rate.rate = rate.rate
end if cache
- rescue ActiveRecord::RecordNotUnique
- # Race condition: another process inserted between our SELECT and INSERT
- # Retry by finding the existing record
- ExchangeRate.find_by!(
+ rescue ActiveRecord::RecordNotUnique, ActiveRecord::RecordInvalid
+ # Race condition: another process inserted between our SELECT and INSERT.
+ # RecordNotUnique = DB unique constraint; RecordInvalid = model uniqueness
+ # validation fired before the DB got a chance to reject it. Both are safe
+ # to handle by reading back the record that the other process just saved.
+ return ExchangeRate.find_by!(
from_currency: rate.from,
to_currency: rate.to,
date: rate.date