Skip to content

Instantly share code, notes, and snippets.

@henrik
Created September 2, 2009 20:58
Show Gist options
  • Save henrik/179953 to your computer and use it in GitHub Desktop.
Save henrik/179953 to your computer and use it in GitHub Desktop.
Simple MySQL "LIKE"-based infix search in Rails. Case and accent insensitive.
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