Reset counters for points counter cache

This commit is contained in:
Eugene Burmakin 2025-08-26 15:26:05 +02:00
parent 02e6fb8a85
commit b8d69a6797
5 changed files with 13 additions and 13 deletions

View file

@ -16,12 +16,7 @@ class DataMigrations::PrefillPointsCounterCacheJob < ApplicationJob
private
def prefill_counter_for_user(user_id)
user = User.find(user_id)
points_count = user.points.count
User.where(id: user_id).update_all(points_count: points_count)
Rails.logger.info "Updated points_count for user #{user_id}: #{points_count}"
User.reset_counters(user_id, :points)
rescue ActiveRecord::RecordNotFound
Rails.logger.warn "User #{user_id} not found, skipping counter cache update"
end

View file

@ -28,6 +28,7 @@ class Imports::Create
schedule_stats_creating(user.id)
schedule_visit_suggesting(user.id, import)
update_import_points_count(import)
User.reset_counters(user.id, :points)
rescue StandardError => e
import.update!(status: :failed)
broadcast_status_update

View file

@ -1,15 +1,11 @@
class AddPointsCountToUsers < ActiveRecord::Migration[8.0]
def change
add_column :users, :points_count, :integer, default: 0, null: false
# Initialize counter cache for existing users using background job
reversible do |dir|
dir.up do
# Enqueue job to prefill counter cache in background
# This prevents the migration from blocking on large datasets
say_with_time "Enqueueing job to prefill points counter cache" do
DataMigrations::PrefillPointsCounterCacheJob.perform_later
end
DataMigrations::PrefillPointsCounterCacheJob.perform_later
end
end
end

1
db/schema.rb generated
View file

@ -10,7 +10,6 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[8.0].define(version: 2025_08_23_125940) do
# These are extensions that must be enabled in order to support this database
enable_extension "pg_catalog.plpgsql"

View file

@ -27,6 +27,15 @@ RSpec.describe Imports::Create do
expect(import.reload.source).to eq('owntracks')
end
it 'resets points counter cache' do
allow(User).to receive(:reset_counters)
service.call
expect(User).to have_received(:reset_counters).with(user.id, :points)
end
context 'when import succeeds' do
it 'sets status to completed' do
service.call