Skip to content

Instantly share code, notes, and snippets.

@Florian95
Forked from jimworm/simple_search.rb
Created April 24, 2012 11:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Florian95/2478919 to your computer and use it in GitHub Desktop.
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)
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
@Florian95
Copy link
Author

Add Support for 3.2 and remove deprecated "write_inheritable_attribute"

@tebayoso
Copy link

tebayoso commented Jul 3, 2014

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