diff --git a/plugins/pg_search/lib/ext/active_record.rb b/plugins/pg_search/lib/ext/active_record.rb index 6b8712d..d47e713 100644 --- a/plugins/pg_search/lib/ext/active_record.rb +++ b/plugins/pg_search/lib/ext/active_record.rb @@ -4,7 +4,8 @@ class ActiveRecord::Base def self.pg_search_plugin_search(query) filtered_query = query.gsub(/[\|\(\)\\\/\s\[\]'"*%&!:]/,' ').split.map{|w| w += ":*"}.join('|') if defined?(self::SEARCHABLE_FIELDS) - where("to_tsvector('simple', #{pg_search_plugin_fields}) @@ to_tsquery('#{filtered_query}')") + where("to_tsvector('simple', #{pg_search_plugin_fields}) @@ to_tsquery('#{filtered_query}')"). + order("ts_rank(to_tsvector('simple', #{pg_search_plugin_fields}), to_tsquery('#{filtered_query}')) DESC") else raise "No searchable fields defined for #{self.name}" end diff --git a/plugins/pg_search/test/unit/pg_search_plugin_test.rb b/plugins/pg_search/test/unit/pg_search_plugin_test.rb index 6069f37..19ce88e 100644 --- a/plugins/pg_search/test/unit/pg_search_plugin_test.rb +++ b/plugins/pg_search/test/unit/pg_search_plugin_test.rb @@ -21,6 +21,14 @@ class PgSearchPluginTest < ActiveSupport::TestCase assert_includes search(Profile, 'admin deb'), profile2 end + should 'rank profiles based on the search entry' do + profile1 = fast_create(Profile, :identifier => 'profile1', :name => 'debugger') + profile2 = fast_create(Profile, :identifier => 'profile2', :name => 'profile admin debugger') + profile3 = fast_create(Profile, :identifier => 'profile3', :name => 'admin debugger') + profile4 = fast_create(Profile, :identifier => 'profile4', :name => 'simple user') + assert_equal [profile2, profile3, profile1, profile4], search(Profile, 'profile admin deb') + end + should 'locate profile escaping special characters' do profile = fast_create(Profile, :name => 'John', :identifier => 'waterfall') assert_includes search(Profile, ') ( /\/\/\/\/\ o_o oOo o_o /\/\/\/\/\ ) ((tx waterfall)'), profile -- libgit2 0.21.2