Abstracting a search feature

Does anyone have any suggestions at all? :frowning:

I just found some old code I wrote that adds a basic search method to active record. You'll probably want to extend it (add fix bugs!) but hopefully it'll give you a starting point and show you how you can approach this problem.

module ActiveRecord   class Base     def self.search(keywords)       keywords = keywords.split(" ")       sql_conditions = ""

      keywords.each do |word|         sql_conditions << "("

        columns.each do |column|           sql_conditions << "#{column.name} LIKE '%#{word}%' OR " if column.type == :string         end

        sql_conditions.gsub!(/OR $/, '')         sql_conditions << ") AND "       end       sql_conditions.gsub!(/ AND $/, '')

      find(:all, :conditions => sql_conditions)     end   end end

Stick that in a file called active_record_extensions.rb (or something) and save it to lib/. You'll need add a require line to your environment.rb: require 'lib/active_record_extensions'

You should then be able to do a basic search like this: ClassMate.search("stephen bartholomew")

Hope that helps,