From 4cd575fa238bfc3008f57b9d01ce768cd16b405f Mon Sep 17 00:00:00 2001 From: soky srm Date: Mon, 24 Nov 2025 17:54:18 +0100 Subject: [PATCH] Rate exchange fix (#377) * FIX cache hit issue * Change to proper method * FIX cache is read heavy, so change to find --- app/models/exchange_rate/provided.rb | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) 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