-
-
Save Florian95/2478919 to your computer and use it in GitHub Desktop.
Simple search for all Rails 3.2 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 | |
class_attribute :simple_search_fields | |
self.simple_search_fields = attrs.flatten | |
def simple_search(search_string) | |
return find(:all) if search_string.nil? || search_string.blank? | |
attrs = self.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 |
That might sound like a basic question. But where do I have to implement it?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add Support for 3.2 and remove deprecated "write_inheritable_attribute"