Module: MultiColumnSearch
- Defined in:
- lib/multi_column_search.rb
Instance Method Summary collapse
- #get_multi_column_pattern(match, term) ⇒ Object
-
#multi_column_search(*args) ⇒ Object
Adds a Model.search(‘term1 term2’) method that searches across SEARCH_COLUMNS for ORed across columns.
Instance Method Details
#get_multi_column_pattern(match, term) ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/multi_column_search.rb', line 34 def get_multi_column_pattern(match, term) case(match) when :exact term when :start term + '%' when :middle '%' + term + '%' when :end '%' + term else raise "Unexpected match type: #{[:match]}" end end |
#multi_column_search(*args) ⇒ Object
Adds a Model.search(‘term1 term2’) method that searches across SEARCH_COLUMNS for ORed across columns.
class Company
multi_column_search :name, :address, :city, :state, :zip, :phone
end
Company.search('Jack Russ') # => any company, street, city that match Jack Russ
Company.search('29464') # => any company with zip code 29464
Company.search('Mount P')
# => any company with 'Mount P' in the city
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# File 'lib/multi_column_search.rb', line 15 def multi_column_search(*args) = args. columns = args [:match] ||= :start [:name] ||= 'search' # PostgreSQL LIKE is case-sensitive, use ILIKE for case-insensitive like = connection.adapter_name == "PostgreSQL" ? "ILIKE" : "LIKE" scope [:name], lambda { |terms| terms = terms.split.join('%') conditions = terms.split.inject(where(nil)) do |acc, term| pattern = get_multi_column_pattern [:match], term where(columns.collect { |column| "#{table_name}.#{column} #{like} :pattern" }.join(' OR '), {:pattern => pattern}) end } end |