Correct bad where clause when no category/user found

This commit is contained in:
Sam 2015-08-14 11:53:16 +10:00
parent e9e5a6c122
commit ad2de1804e
2 changed files with 16 additions and 6 deletions
lib
spec/components

View file

@ -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|

View file

@ -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