diff --git a/app/models/concerns/sort_handler.rb b/app/models/concerns/sort_handler.rb index 065fa7fea..519eccc8b 100644 --- a/app/models/concerns/sort_handler.rb +++ b/app/models/concerns/sort_handler.rb @@ -19,7 +19,7 @@ module SortHandler end def sort_on_waiting_since(sort_direction = :asc) - order(generate_sql_query("waiting_since #{sort_direction.to_s.upcase} NULLS LAST, created_at ASC")) + order(generate_sql_query("(waiting_since IS NULL), waiting_since #{sort_direction.to_s.upcase}, created_at ASC")) end def last_messaged_conversations diff --git a/spec/models/conversation_spec.rb b/spec/models/conversation_spec.rb index 89c090207..0bf90859e 100644 --- a/spec/models/conversation_spec.rb +++ b/spec/models/conversation_spec.rb @@ -879,6 +879,31 @@ RSpec.describe Conversation do conversation_4.id ] end + + context 'when some conversations have a null waiting_since' do + before do + # rubocop:disable Rails/SkipsModelValidations + conversation_5.update_column(:waiting_since, nil) + conversation_2.update_column(:waiting_since, nil) + # rubocop:enable Rails/SkipsModelValidations + end + + it 'places null waiting_since conversations at the end in ascending order' do + records = described_class.sort_on_waiting_since + expect(records.map(&:id)).to eq [ + conversation_4.id, conversation_6.id, conversation_7.id, conversation_3.id, conversation_1.id, + conversation_5.id, conversation_2.id + ] + end + + it 'places null waiting_since conversations at the end in descending order' do + records = described_class.sort_on_waiting_since(:desc) + expect(records.map(&:id)).to eq [ + conversation_1.id, conversation_3.id, conversation_7.id, conversation_6.id, conversation_4.id, + conversation_5.id, conversation_2.id + ] + end + end end end