FIX: Care for nil counts when ordering

This commit is contained in:
Nat 2024-08-12 15:50:42 +08:00
parent a1243b094f
commit 1f5c7226d4
No known key found for this signature in database
GPG Key ID: 4938B35D927EC773
2 changed files with 7 additions and 4 deletions

View File

@ -121,7 +121,9 @@ after_initialize do
filter_order_votes = ->(scope, order_direction) do
scope = scope.joins(:topic_vote_count)
scope.order("topic_voting_topic_vote_count.votes_count #{order_direction}")
scope.order(
"COALESCE(topic_voting_topic_vote_count.votes_count, 0)::integer #{order_direction}",
)
end
add_filter_custom_filter("order:votes", &filter_order_votes)

View File

@ -4,7 +4,8 @@ RSpec.describe TopicsFilter do
describe "adding order:votes to DiscoursePluginRegistry.custom_filter_mappings" do
fab!(:topic_high) { Fabricate(:topic_voting_vote_count, votes_count: 10).topic }
fab!(:topic_med) { Fabricate(:topic_voting_vote_count, votes_count: 5).topic }
fab!(:topic_low) { Fabricate(:topic_voting_vote_count, votes_count: 1).topic }
fab!(:topic_low) { Fabricate(:topic_voting_vote_count, votes_count: 0).topic }
fab!(:topic_nil) { Fabricate(:topic_voting_vote_count, votes_count: nil).topic }
it "sorts votes in ascending order" do
expect(
@ -12,13 +13,13 @@ RSpec.describe TopicsFilter do
.new(guardian: Guardian.new)
.filter_from_query_string("order:votes-asc")
.pluck(:id),
).to eq([topic_low.id, topic_med.id, topic_high.id])
).to eq([topic_low.id, topic_nil.id, topic_med.id, topic_high.id])
end
it "sorts votes in default descending order" do
expect(
TopicsFilter.new(guardian: Guardian.new).filter_from_query_string("order:votes").pluck(:id),
).to eq([topic_high.id, topic_med.id, topic_low.id])
).to eq([topic_high.id, topic_med.id, topic_low.id, topic_nil.id])
end
end
end