Created
June 16, 2011 15:36
-
-
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)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
Usage:
In your model class:
has_simple_search(:attribute1, :attribute2...)
To search:
Model.simple_search('search string')