Skip to content

Instantly share code, notes, and snippets.

@mdub
Created August 3, 2011 07:05
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 mdub/1122069 to your computer and use it in GitHub Desktop.
Save mdub/1122069 to your computer and use it in GitHub Desktop.
PostgreSQL full-text search support for ActiveRecord
module PostgresqlFullTextSearch
extend ActiveSupport::Concern
module ClassMethods
def tsearch(column_names, terms)
raise(ArgumentError) if terms.nil?
return self.scoped if terms == ""
vectors = Array(column_names).map do |column_name|
"to_tsvector(coalesce(#{column_name}, ''))"
end
conditions = vectors.join(' || ') + " @@ to_tsquery(?)"
tokens = terms.split.map do |word|
connection.quote(word) + ":*"
end
query = tokens.join(" & ")
where(conditions, query)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment