FIX: Do not raise error if most liked user is deleted

FIX: Do not raise error if most liked user is deleted
diff --git a/app/models/user_summary.rb b/app/models/user_summary.rb
index cea0d05..00cf516 100644
--- a/app/models/user_summary.rb
+++ b/app/models/user_summary.rb
@@ -192,10 +192,12 @@ protected
 
     lookup = AvatarLookup.new(user_ids)
     user_ids.map do |user_id|
+      lookup_hash = lookup[user_id]
+
       UserWithCount.new(
-        lookup[user_id].attributes.merge(count: user_hash[user_id])
-      )
-    end.sort_by { |u| -u[:count] }
+        lookup_hash.attributes.merge(count: user_hash[user_id])
+      ) if lookup_hash.present?
+    end.compact.sort_by { |u| -u[:count] }
   end
 
 end
diff --git a/spec/models/user_summary_spec.rb b/spec/models/user_summary_spec.rb
index 4c0bfe7..84fab05 100644
--- a/spec/models/user_summary_spec.rb
+++ b/spec/models/user_summary_spec.rb
@@ -38,4 +38,22 @@ describe UserSummary do
     expect(summary.top_categories.length).to eq(0)
   end
 
+  it "is robust enough to handle bad data" do
+    UserActionCreator.enable
+
+    liked_post = create_post
+    user = Fabricate(:user)
+    PostAction.act(user, liked_post, PostActionType.types[:like])
+
+    users = UserSummary.new(user, Guardian.new).most_liked_users
+
+    expect(users.map(&:id)).to eq([liked_post.user_id])
+
+    # really we should not be corrupting stuff like this
+    # but in production dbs this can happens sometimes I guess
+    liked_post.user.delete
+
+    users = UserSummary.new(user, Guardian.new).most_liked_users
+    expect(users).to eq([])
+  end
 end

GitHub
sha: a16bb328

2 Likes

This commit has been mentioned on Discourse Meta. There might be relevant details there: