Skip to content

Commit 9e9ac28

Browse files
authored
FIX: Some solved topics have no answers (#350)
As part of #342, some discrepancies in the old implementation resulted in solved topics linking to posts that do not exist (dangling custom field value). Causing us to see the following when there are no `answer_post` ``` NoMethodError (undefined method `user' for nil) ``` This PR prevents the error.
1 parent ad2555f commit 9e9ac28

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

lib/discourse_solved/topic_view_serializer_extension.rb

+2-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,8 @@ module DiscourseSolved::TopicViewSerializerExtension
66
prepended { attributes :accepted_answer }
77

88
def include_accepted_answer?
9-
SiteSetting.solved_enabled? && object.topic.solved.present?
9+
SiteSetting.solved_enabled? && object.topic.solved.present? &&
10+
object.topic.solved.answer_post.present?
1011
end
1112

1213
def accepted_answer
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
# frozen_string_literal: true
2+
3+
describe TopicViewSerializer do
4+
fab!(:topic)
5+
fab!(:post1) { Fabricate(:post, topic:) }
6+
fab!(:post2) { Fabricate(:post, topic:) }
7+
fab!(:user)
8+
9+
before { SiteSetting.solved_enabled = true }
10+
11+
describe "#accepted_answer" do
12+
it "returns the accepted answer post when the topic has an accepted answer" do
13+
Fabricate(:solved_topic, topic: topic, answer_post: post2)
14+
serializer = TopicViewSerializer.new(TopicView.new(topic), scope: Guardian.new(user))
15+
serialized = serializer.as_json
16+
expect(serialized[:topic_view][:accepted_answer][:post_number]).to eq(post2.post_number)
17+
end
18+
19+
it "returns nil when the topic does not have an accepted answer" do
20+
unsolved_topic = Fabricate(:topic)
21+
serializer = TopicViewSerializer.new(TopicView.new(unsolved_topic), scope: Guardian.new(user))
22+
serialized = serializer.as_json
23+
expect(serialized[:accepted_answer]).to be_nil
24+
end
25+
26+
it "returns nil when the accepted answer post does not exist" do
27+
weird_topic = Fabricate(:solved_topic)
28+
weird_topic.update!(answer_post_id: 19_238_319)
29+
serializer =
30+
TopicViewSerializer.new(TopicView.new(weird_topic.topic), scope: Guardian.new(user))
31+
serialized = serializer.as_json
32+
expect(serialized[:accepted_answer]).to be_nil
33+
end
34+
end
35+
end

0 commit comments

Comments
 (0)