Created
September 2, 2009 20:58
-
-
Save henrik/179953 to your computer and use it in GitHub Desktop.
Simple MySQL "LIKE"-based infix search in Rails. Case and accent insensitive.
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 Foo < ActiveRecord::Base | |
named_scope :infix_search, lambda { |string| | |
if string.blank? | |
{} | |
else | |
tokens = string.chars.downcase.split.uniq.first(10) # Avoid too heavy queries. | |
fields = %w[ | |
foo.bar foo.baz | |
oink.boink | |
] | |
like_query = %{ LOWER(CONCAT_WS(' ', #{fields.join(', ')})) COLLATE utf8_general_ci LIKE ? } | |
templates = Array.new(tokens.length) { like_query }.join(' AND ') | |
values = tokens.map {|token| "%#{token}%" } | |
{ :include => :oink, :conditions => [templates, *values] } | |
end | |
} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment