diff --git a/app/models/exchange_rate/provided.rb b/app/models/exchange_rate/provided.rb index 6eadf92b8..c4e894d26 100644 --- a/app/models/exchange_rate/provided.rb +++ b/app/models/exchange_rate/provided.rb @@ -19,12 +19,23 @@ module ExchangeRate::Provided return nil unless response.success? # Provider error rate = response.data - ExchangeRate.find_or_create_by!( - from_currency: rate.from, - to_currency: rate.to, - date: rate.date, - rate: rate.rate - ) if cache + begin + ExchangeRate.find_or_create_by!( + from_currency: rate.from, + to_currency: rate.to, + date: rate.date + ) 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!( + from_currency: rate.from, + to_currency: rate.to, + date: rate.date + ) if cache + end rate end