FIX: Reviewable counts were not updating properly

FIX: Reviewable counts were not updating properly

Sometimes sidekiq is so fast that it starts jobs before transactions have comitted. This patch moves the message bus stuff until after things have comitted.

diff --git a/app/models/reviewable.rb b/app/models/reviewable.rb
index 57d9271..7e56ad0 100644
--- a/app/models/reviewable.rb
+++ b/app/models/reviewable.rb
@@ -29,9 +29,12 @@ class Reviewable < ActiveRecord::Base
   has_many :reviewable_scores
 
   after_create do
+    log_history(:created, created_by)
+  end
+
+  after_commit do
     DiscourseEvent.trigger(:reviewable_created, self)
     Jobs.enqueue(:notify_reviewable, reviewable_id: self.id) if pending?
-    log_history(:created, created_by)
   end
 
   def self.statuses
@@ -208,17 +211,20 @@ class Reviewable < ActiveRecord::Base
     raise InvalidAction.new(action_id, self.class) unless respond_to?(perform_method)
 
     result = nil
+    update_count = false
     Reviewable.transaction do
       increment_version!(args[:version])
       result = send(perform_method, performed_by, args)
 
       if result.success?
-        transition_to(result.transition_to, performed_by) if result.transition_to
+        update_count = transition_to(result.transition_to, performed_by) if result.transition_to
         update_flag_stats(**result.update_flag_stats) if result.update_flag_stats
 
         recalculate_score if result.recalculate_score
       end
     end
+    Jobs.enqueue(:notify_reviewable, reviewable_id: self.id) if update_count
+
     result
   end
 
@@ -239,7 +245,7 @@ class Reviewable < ActiveRecord::Base
       )
     end
 
-    Jobs.enqueue(:notify_reviewable, reviewable_id: self.id) if was_pending
+    was_pending
   end
 
   def post_options
diff --git a/spec/models/reviewable_flagged_post_spec.rb b/spec/models/reviewable_flagged_post_spec.rb
index 7ea36fb..ab63024 100644
--- a/spec/models/reviewable_flagged_post_spec.rb
+++ b/spec/models/reviewable_flagged_post_spec.rb
@@ -52,7 +52,6 @@ RSpec.describe ReviewableFlaggedPost, type: :model do
         expect(reviewable.actions_for(guardian).has?(:delete_and_ignore_replies)).to eq(true)
       end
 
-
       it "returns appropriate actions for a hidden post" do
         post.update(hidden: true, hidden_at: Time.now)
         expect(reviewable.actions_for(guardian).has?(:agree_and_hide)).to eq(false)
@@ -162,7 +161,6 @@ RSpec.describe ReviewableFlaggedPost, type: :model do
       expect(reply.reload.deleted_at).to be_present
     end
 
-
     it "disagrees with the flags" do
       reviewable.perform(moderator, :disagree)
       expect(reviewable).to be_rejected

GitHub sha: df48c657

1 Like

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