From ad2de1804e7aac8ec42d4fd457842da871257fe4 Mon Sep 17 00:00:00 2001 From: Sam Date: Fri, 14 Aug 2015 11:53:16 +1000 Subject: [PATCH] Correct bad where clause when no category/user found --- lib/search.rb | 16 ++++++++++++---- spec/components/search_spec.rb | 6 ++++-- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/lib/search.rb b/lib/search.rb index a22766ef190..0b3bf5328c4 100644 --- a/lib/search.rb +++ b/lib/search.rb @@ -215,13 +215,21 @@ class Search end advanced_filter(/category:(.+)/) do |posts,match| - category_id = Category.find_by('name ilike ? OR id = ?', match, match.to_i).try(:id) - posts.where("topics.category_id = ?", category_id) + category_id = Category.where('name ilike ? OR id = ?', match, match.to_i).pluck(:id).first + if category_id + posts.where("topics.category_id = ?", category_id) + else + posts.where("1 = 0") + end end advanced_filter(/user:(.+)/) do |posts,match| - user_id = User.find_by('username_lower = ? OR id = ?', match.downcase, match.to_i).try(:id) - posts.where("posts.user_id = #{user_id}") + user_id = User.where('username_lower = ? OR id = ?', match.downcase, match.to_i).pluck(:id).first + if user_id + posts.where("posts.user_id = #{user_id}") + else + posts.where("1 = 0") + end end advanced_filter(/min_age:(\d+)/) do |posts,match| diff --git a/spec/components/search_spec.rb b/spec/components/search_spec.rb index 4d94c2e5eeb..498887c115b 100644 --- a/spec/components/search_spec.rb +++ b/spec/components/search_spec.rb @@ -373,10 +373,10 @@ describe Search do describe 'Advanced search' do - it 'supports min_age and max_age in:first' do + it 'supports min_age and max_age in:first user:' do topic = Fabricate(:topic, created_at: 3.months.ago) Fabricate(:post, raw: 'hi this is a test 123 123', topic: topic) - Fabricate(:post, raw: 'boom boom shake the room', topic: topic) + _post = Fabricate(:post, raw: 'boom boom shake the room', topic: topic) expect(Search.execute('test min_age:100').posts.length).to eq(1) expect(Search.execute('test min_age:10').posts.length).to eq(0) @@ -387,6 +387,8 @@ describe Search do expect(Search.execute('boom').posts.length).to eq(1) expect(Search.execute('boom in:first').posts.length).to eq(0) + expect(Search.execute('user:nobody').posts.length).to eq(0) + expect(Search.execute("user:#{_post.user.username}").posts.length).to eq(1) end it 'can search numbers correctly, and match exact phrases' do