diff --git a/lib/search.rb b/lib/search.rb index 80b0a62e1d7..60301ff3322 100644 --- a/lib/search.rb +++ b/lib/search.rb @@ -149,6 +149,9 @@ class Search elsif word == 'status:closed' @status = :closed nil + elsif word == 'order:latest' + @order = :latest + nil else word end @@ -274,15 +277,23 @@ class Search end - posts = posts.order("TS_RANK_CD(TO_TSVECTOR(#{query_locale}, topics.title), #{ts_query}) DESC") - - data_ranking = "TS_RANK_CD(post_search_data.search_data, #{ts_query})" - if opts[:aggregate_search] - posts = posts.order("SUM(#{data_ranking}) DESC") + if @order == :latest + if opts[:aggregate_search] + posts = posts.order("MAX(posts.created_at) DESC") + else + posts = posts.order("posts.created_at DESC") + end else - posts = posts.order("#{data_ranking} DESC") + posts = posts.order("TS_RANK_CD(TO_TSVECTOR(#{query_locale}, topics.title), #{ts_query}) DESC") + + data_ranking = "TS_RANK_CD(post_search_data.search_data, #{ts_query})" + if opts[:aggregate_search] + posts = posts.order("SUM(#{data_ranking}) DESC") + else + posts = posts.order("#{data_ranking} DESC") + end + posts = posts.order("topics.bumped_at DESC") end - posts = posts.order("topics.bumped_at DESC") if secure_category_ids.present? posts = posts.where("(categories.id IS NULL) OR (NOT categories.read_restricted) OR (categories.id IN (?))", secure_category_ids).references(:categories) @@ -331,7 +342,6 @@ class Search .joins("JOIN (#{post_sql}) x ON x.id = posts.topic_id AND x.post_number = posts.post_number") .order('row_number') - posts.each do |post| @results.add(post) end diff --git a/spec/components/search_spec.rb b/spec/components/search_spec.rb index dea92fa5579..0ac9a78c384 100644 --- a/spec/components/search_spec.rb +++ b/spec/components/search_spec.rb @@ -321,6 +321,16 @@ describe Search do Search.execute('test status:closed').posts.length.should == 1 Search.execute('test status:open').posts.length.should == 0 + end + + it 'can find by latest' do + topic1 = Fabricate(:topic, title: 'I do not like that Sam I am') + post1 = Fabricate(:post, topic: topic1) + + post2 = Fabricate(:post, raw: 'that Sam I am, that Sam I am') + + Search.execute('sam').posts.map(&:id).should == [post1.id, post2.id] + Search.execute('sam order:latest').posts.map(&:id).should == [post2.id, post1.id] end end