Add consistency check to revoke duplicate badges.

This commit is contained in:
Vikhyat Korrapati 2014-06-28 00:57:26 +05:30
parent 2e52f795ea
commit 83749779cc
2 changed files with 12 additions and 0 deletions

View File

@ -9,6 +9,7 @@ module Jobs
Group.refresh_automatic_groups!
Notification.ensure_consistency!
UserAction.ensure_consistency!
UserBadge.ensure_consistency!
end
end
end

View File

@ -17,6 +17,17 @@ class UserBadge < ActiveRecord::Base
after_destroy do
Badge.decrement_counter 'grant_count', self.badge_id
end
# Make sure we don't have duplicate badges.
def self.ensure_consistency!
dup_ids = []
# Single grant badges shouldn't have duplicates at all.
dup_ids += exec_sql("SELECT u1.id FROM user_badges u1, user_badges u2, badges WHERE u1.badge_id = badges.id AND u1.user_id = u2.user_id AND u1.badge_id = u2.badge_id AND (NOT badges.multiple_grant) AND u1.granted_at > u2.granted_at").to_a
# Multiple grant badges can have duplicates but not with the same post_ids.
dup_ids += exec_sql("SELECT u1.id FROM user_badges u1, user_badges u2, badges WHERE u1.badge_id = badges.id AND u1.user_id = u2.user_id AND u1.badge_id = u2.badge_id AND badges.multiple_grant AND u1.post_id = u2.post_id AND u1.granted_at > u2.granted_at").to_a
dup_ids = dup_ids.map {|x| x["id"].to_i }
UserBadge.where(id: dup_ids).destroy_all
end
end
# == Schema Information