Created
June 23, 2012 17:00
-
-
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
This file contains 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 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