FIX: no error when double save post with poll (PR #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 attribute 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.

GitHub

this feels a bit weird. a side effect of calling validations is setting / resetting a var to .

Is there any other way we can do this fix? More nil checks elsewhere?

yeah, it was written this way discourse/plugin.rb at 303de2d9c143cf5f8b207bc184a442b4405eb634 · discourse/discourse · GitHub

I will try to fix it properly

@ZogStriP are you happy with after_save doing the reset here?

Yes, I think that’s fine.

        self.extracted_polls = nil

nil or {} would be slightly more correct.

Not sure how adding this line test for “double save” though. I think it requires the discourse-category-experts plugin to be installed?

You are right, it is not neccessary.

Without fix, just save! twice is raising an error:

 post = Fabricate(:post, raw: "[poll]\n- A\n- B\n[/poll]")
 post.save!

The reason for that is that raw is same and extraced_polls were not reset: