From 3d406b047c1548e8ffee9346855b8d3814ca3e35 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?R=C3=A9gis=20Hanol?= Date: Mon, 24 Apr 2017 22:36:07 +0200 Subject: [PATCH] PERF: much faster Badge.ensure_consistency --- app/models/badge.rb | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/app/models/badge.rb b/app/models/badge.rb index 5ffde4726b3..25b2a38105b 100644 --- a/app/models/badge.rb +++ b/app/models/badge.rb @@ -132,12 +132,24 @@ class Badge < ActiveRecord::Base exec_sql <<-SQL.squish DELETE FROM user_badges USING user_badges ub - LEFT JOIN users u ON u.id = ub.user_id - WHERE u.id IS NULL - AND user_badges.id = ub.id + LEFT JOIN users u ON u.id = ub.user_id + WHERE u.id IS NULL + AND user_badges.id = ub.id SQL - Badge.find_each(&:reset_grant_count!) + exec_sql <<-SQL.squish + WITH X AS ( + SELECT badge_id + , COUNT(user_id) users + FROM user_badges + GROUP BY badge_id + ) + UPDATE badges + SET grant_count = X.users + FROM X + WHERE id = X.badge_id + AND grant_count <> X.users + SQL end def awarded_for_trust_level?