Skip to content

Instantly share code, notes, and snippets.

@warmwaffles
Created June 23, 2012 17:00
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 warmwaffles/2979011 to your computer and use it in GitHub Desktop.
Save warmwaffles/2979011 to your computer and use it in GitHub Desktop.
Have you wanted to ever fuzzy search on your model without actually running Solr or Sphinx? Well this little function can help ease you in
class Widget < ActiveRecord::Base
#
# ..... extra crap here .....
#
scope :active, where(:status => [:active])
#
# This will fuzzy search the model for the provided query. It will split your
# query string on the whitespace and search the models.
#
# You can even further chain the query with scopes like so:
#
# ```rb
# Widget.search('foo bar qux').active.limit(10)
# ```
#
def self.joined_search(query)
query = query.split(/\s+/)
fields = {
users: [:email, :first_name, :last_name],
widgets: [:field, :another_field]
}
params = Array.new
last = Array.new
query.each do |q|
fields.each do |table,cols|
cols.each do |col|
params << %Q{"#{table}"."#{col}" LIKE ?}
last << "%#{q}%"
end
end
end
sql = [params.join(' OR ')] + last
joins(:users).where(sql)
end
#
# This will search only this model. It will not join another table to search.
# This method can be chained as well with other active record statements
#
def self.search(query)
query = query.split(/\s+/)
fields = self.attribute_names # you can specify an array of symbols if you want [:field, :field2]
params = Array.new
last = Array.new
query.each do |q|
fields.each do |f|
params << %Q{"#{self.table_name}"."#{f}" LIKE ?}
last << "%#{q}%"
end
end
sql = [params.join(' OR ')] + last
where(sql)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment