Skip to content

A platform for community discussion. Free, open, simple.

FIX: Error when loading a channel with threading enabled but no threads (#22434)

Alan Guo Xiang Tan1e26a521c2fc
diff --git a/plugins/chat/app/services/chat/lookup_channel_threads.rb b/plugins/chat/app/services/chat/lookup_channel_threads.rb
index 3622b0e4aeb..352498b4a49 100644
--- a/plugins/chat/app/services/chat/lookup_channel_threads.rb
+++ b/plugins/chat/app/services/chat/lookup_channel_threads.rb
@@ -84,24 +84,26 @@ module Chat
threads = unread_threads + read_threads
- last_replies =
- Chat::Message
- .strict_loading
- .includes(:user, :uploads)
- .from(<<~SQL)
- (
- SELECT thread_id, MAX(created_at) AS latest_created_at, MAX(id) AS latest_message_id
- FROM chat_messages
- WHERE thread_id IN (#{threads.map(&:id).join(",")})
- GROUP BY thread_id
- ) AS last_replies_subquery
- SQL
- .joins(
- "INNER JOIN chat_messages ON chat_messages.id = last_replies_subquery.latest_message_id",
- )
- .index_by(&:thread_id)
+ if threads.present?
+ last_replies =
+ Chat::Message
+ .strict_loading
+ .includes(:user, :uploads)
+ .from(<<~SQL)
+ (
+ SELECT thread_id, MAX(created_at) AS latest_created_at, MAX(id) AS latest_message_id
+ FROM chat_messages
+ WHERE thread_id IN (#{threads.map(&:id).join(",")})
+ GROUP BY thread_id
+ ) AS last_replies_subquery
+ SQL
+ .joins(
+ "INNER JOIN chat_messages ON chat_messages.id = last_replies_subquery.latest_message_id",
+ )
+ .index_by(&:thread_id)
- threads.each { |thread| thread.last_reply = last_replies[thread.id] }
+ threads.each { |thread| thread.last_reply = last_replies[thread.id] }
+ end
threads
end
diff --git a/plugins/chat/spec/services/chat/lookup_channel_threads_spec.rb b/plugins/chat/spec/services/chat/lookup_channel_threads_spec.rb
index cda03e1c25f..f724565e1c3 100644
--- a/plugins/chat/spec/services/chat/lookup_channel_threads_spec.rb
+++ b/plugins/chat/spec/services/chat/lookup_channel_threads_spec.rb
@@ -10,6 +10,7 @@ RSpec.describe Chat::LookupChannelThreads do
fab!(:current_user) { Fabricate(:user) }
fab!(:channel) { Fabricate(:chat_channel, threading_enabled: true) }
+ fab!(:channel_with_no_threads) { Fabricate(:chat_channel, threading_enabled: true) }
fab!(:thread_1) { Fabricate(:chat_thread, channel: channel) }
fab!(:thread_2) { Fabricate(:chat_thread, channel: channel) }
fab!(:thread_3) { Fabricate(:chat_thread, channel: channel) }
@@ -32,6 +33,12 @@ RSpec.describe Chat::LookupChannelThreads do
end
end
+ it "does not return any threads when a channel has no threads" do
+ expect(
+ described_class.call(channel_id: channel_with_no_threads.id, guardian:).threads,
+ ).to eq([])
+ end
+
context "when all steps pass" do
before do
msg_1 =