FIX: no error when double save post with poll (#13111)

FIX: no error when double save post with poll (#13111)

Some plugins hook into Post after save to set custom fields and save again.

For example: discourse-category-experts/post_handler.rb at main · discourse/discourse-category-experts · GitHub

Problem is that in case like that raw_changed? is false but all callback are triggered. extracted_polls is class atribute therefore that should be reset with each attempt.

That was causing an error:

#<ActiveRecord::RecordNotUnique: PG::UniqueViolation: ERROR:  duplicate key value violates unique constraint 
"index_polls_on_post_id_and_name" DETAIL:  Key (post_id, name)=(8967, poll) already exists.
diff --git a/plugins/poll/plugin.rb b/plugins/poll/plugin.rb
index b5f657f..02224ae 100644
--- a/plugins/poll/plugin.rb
+++ b/plugins/poll/plugin.rb
@@ -467,6 +467,7 @@ after_initialize do
 
       after_save do
         polls = self.extracted_polls
+        self.extracted_polls = nil
         next if polls.blank? || !polls.is_a?(Hash)
         post = self
 
diff --git a/plugins/poll/spec/models/poll_spec.rb b/plugins/poll/spec/models/poll_spec.rb
index 1b1f8e8..03ebcd2 100644
--- a/plugins/poll/spec/models/poll_spec.rb
+++ b/plugins/poll/spec/models/poll_spec.rb
@@ -81,6 +81,10 @@ describe ::DiscoursePoll::Poll do
 
       expect(poll.post).to eq(post)
     end
+  end
 
+  it "is not throwing an error when double save" do
+    post = Fabricate(:post, raw: "[poll]\n- A\n- B\n[/poll]")
+    expect { post.save! }.not_to raise_error
   end
 end

GitHub sha: 942b9126

This commit appears in #13111 which was approved by ZogStriP. It was merged by lis2.