From 84be92c0671b85ce9ba016b4e867784f7022e5f8 Mon Sep 17 00:00:00 2001 From: David Taylor Date: Tue, 28 Apr 2020 14:43:09 +0100 Subject: [PATCH] FIX: Avoid exception when rendering a poll in a trashed post Maintain the poll belongs_to post relation when a post is trashed --- plugins/poll/app/models/poll.rb | 4 ++-- plugins/poll/spec/models/poll_spec.rb | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/plugins/poll/app/models/poll.rb b/plugins/poll/app/models/poll.rb index 4f7e0bd584a..44ce17f46cf 100644 --- a/plugins/poll/app/models/poll.rb +++ b/plugins/poll/app/models/poll.rb @@ -4,7 +4,7 @@ class Poll < ActiveRecord::Base # because we want to use the 'type' column and don't want to use STI self.inheritance_column = nil - belongs_to :post + belongs_to :post, -> { unscope(:where) } has_many :poll_options, -> { order(:id) }, dependent: :destroy has_many :poll_votes @@ -51,7 +51,7 @@ class Poll < ActiveRecord::Base end def is_me?(user) - user && post.user&.id == user&.id + user && post && post.user&.id == user&.id end def has_voted?(user) diff --git a/plugins/poll/spec/models/poll_spec.rb b/plugins/poll/spec/models/poll_spec.rb index 55e6567d47c..fed3310b84a 100644 --- a/plugins/poll/spec/models/poll_spec.rb +++ b/plugins/poll/spec/models/poll_spec.rb @@ -69,4 +69,18 @@ describe ::DiscoursePoll::Poll do expect(poll.can_see_results?(user)).to eq(true) end end + + describe 'when post is trashed' do + it "maintains the association" do + user = Fabricate(:user) + post = Fabricate(:post, raw: "[poll results=staff_only]\n- A\n- B\n[/poll]", user: user) + poll = post.polls.first + + post.trash! + poll.reload + + expect(poll.post).to eq(post) + end + + end end