Skip to content

Instantly share code, notes, and snippets.

@jimworm
Created June 16, 2011 15:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jimworm/1029512 to your computer and use it in GitHub Desktop.
Save jimworm/1029512 to your computer and use it in GitHub Desktop.
Simple search for all Rails 3 ActiveRecord models on any string column(s)
class ActiveRecord::Base
class << self
def has_simple_search(*attrs)
raise 'has_simple_search expects at least one attribute' if attrs.empty?
instance_eval do # because this is ActiveRecord::Base, the class inherits this
write_inheritable_attribute(:simple_search_fields, attrs.flatten)
def simple_search(search_string)
attrs = read_inheritable_attribute(:simple_search_fields)
like_s = attrs.map{|f| "#{self.table_name}.#{f.to_s} REGEXP ?"}.join(' OR ')
terms = search_string.split(' ').map{|s| Regexp.escape(s.strip)}
where(Array.new(attrs.count, terms.join('|')).unshift(like_s))
end
end
end
end
end
@jimworm
Copy link
Author

jimworm commented Jun 16, 2011

Usage:
In your model class:
has_simple_search(:attribute1, :attribute2...)

To search:
Model.simple_search('search string')

@jimworm
Copy link
Author

jimworm commented Aug 20, 2015

This search has been superseded by searchable, available here: https://gist.github.com/jimworm/35833846e851afec31ab

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment