Skip to content

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

FEATURE: allow searching for oldest topics (#21715)

Samb2e308420539
diff --git a/lib/search.rb b/lib/search.rb
index 03d9e7a5f3d..a11f66b0dbf 100644
--- a/lib/search.rb
+++ b/lib/search.rb
@@ -1124,12 +1124,24 @@ class Search
else
posts = posts.reorder("posts.created_at DESC")
end
+ elsif @order == :oldest
+ if aggregate_search
+ posts = posts.order("MAX(posts.created_at) ASC")
+ else
+ posts = posts.reorder("posts.created_at ASC")
+ end
elsif @order == :latest_topic
if aggregate_search
posts = posts.order("MAX(topics.created_at) DESC")
else
posts = posts.order("topics.created_at DESC")
end
+ elsif @order == :oldest_topic
+ if aggregate_search
+ posts = posts.order("MAX(topics.created_at) ASC")
+ else
+ posts = posts.order("topics.created_at ASC")
+ end
elsif @order == :views
if aggregate_search
posts = posts.order("MAX(topics.views) DESC")
diff --git a/spec/lib/search_spec.rb b/spec/lib/search_spec.rb
index aa889550163..7bb695c2781 100644
--- a/spec/lib/search_spec.rb
+++ b/spec/lib/search_spec.rb
@@ -2002,6 +2002,17 @@ RSpec.describe Search do
expect(Search.execute("l sam").posts.map(&:id)).to eq([post2.id, post1.id])
end
+ it "can find by oldest" do
+ topic1 = Fabricate(:topic, title: "I do not like that Sam I am")
+ post1 = Fabricate(:post, topic: topic1, raw: "sam is a sam sam sam") # score higher
+
+ topic2 = Fabricate(:topic, title: "I do not like that Sam I am 2", created_at: 5.minutes.ago)
+ post2 = Fabricate(:post, topic: topic2, created_at: 5.minutes.ago)
+
+ expect(Search.execute("sam").posts.map(&:id)).to eq([post1.id, post2.id])
+ expect(Search.execute("sam ORDER:oldest").posts.map(&:id)).to eq([post2.id, post1.id])
+ end
+
it "can order by topic creation" do
today = Date.today
yesterday = 1.day.ago
@@ -2039,6 +2050,13 @@ RSpec.describe Search do
expect(Search.execute("Topic order:latest_topic").posts.map(&:id)).to eq(
[category.topic.first_post.id, latest_irrelevant_topic_post.id, old_relevant_topic_post.id],
)
+
+ # push weight to the front to ensure test is correct and is not just a coincidence
+ latest_irrelevant_topic_post.update!(raw: "Topic Topic Topic")
+
+ expect(Search.execute("Topic order:oldest_topic").posts.map(&:id)).to eq(
+ [old_relevant_topic_post.id, latest_irrelevant_topic_post.id, category.topic.first_post.id],
+ )
end
it "can order by topic views" do