Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

jon http://burningbush.us

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Adding text search to ActiveRecord classes

It's fairly easy, but I have no idea how (in)efficient it is.

Here's the important stuff.

In model:
def self.search(terms)
  find_by_sql(["select t.* from table t where #{ (["(lower(t.text_field1) like ? or lower(t.text_field1) like ?)"] * tokens.size).join(" and ") } order by s.created_on desc", *(tokens * 2).sort])
end


Basically it searches any of the fields you specify. If I wanted just one search, I'd drop out the second lower(t.text_field) and change the (tokens*2) to just tokens.

Like this:
def self.search(terms)
  find_by_sql(["select t.* from table t where #{ (["(lower(t.text_field1) like ? )"] * tokens.size).join(" and ") } order by s.created_on desc", tokens])
end


The terms array is just an array of single words, lowercase. They're prepared like this:

 terms = query.split.collect {|c| "%#{c.downcase}%"}


To use this in a controller, I just do this:
 @results = Model.search( @params['query'].split.collect{ |c| "%#{c.downcase}%" } )


Just like that.

From Rory on Rails

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS