<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DZone Snippets: activerecord code</title>
    <link>http://snippets.dzone.com/posts</link>
    <pubDate>Sun, 12 Oct 2008 20:09:54 GMT</pubDate>
    <description>DZone Snippets: activerecord code</description>
    <item>
      <title>Adding text search to ActiveRecord classes</title>
      <link>http://snippets.dzone.com/posts/show/525</link>
      <description>It's fairly easy, but I have no idea how (in)efficient it is.&lt;br /&gt;&lt;br /&gt;Here's the important stuff.&lt;br /&gt;&lt;br /&gt;In model:&lt;br /&gt;&lt;code&gt;&lt;br /&gt;def self.search(terms)&lt;br /&gt;  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])&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;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.&lt;br /&gt;&lt;br /&gt;Like this:&lt;br /&gt;&lt;code&gt;&lt;br /&gt;def self.search(terms)&lt;br /&gt;  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])&lt;br /&gt;end&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;The terms array is just an array of single words, lowercase.  They're prepared like this:&lt;br /&gt;&lt;br /&gt;&lt;code&gt;&lt;br /&gt; terms = query.split.collect {|c| "%#{c.downcase}%"}&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;To use this in a controller, I just do this:&lt;br /&gt;&lt;code&gt;&lt;br /&gt; @results = Model.search( @params['query'].split.collect{ |c| "%#{c.downcase}%" } )&lt;br /&gt;&lt;/code&gt;&lt;br /&gt;&lt;br /&gt;Just like that.&lt;br /&gt;&lt;br /&gt;From &lt;a href="http://www.roryhansen.ca/?p=20"&gt;Rory on Rails&lt;/a&gt;&lt;br /&gt;&lt;br /&gt;</description>
      <pubDate>Fri, 29 Jul 2005 22:55:37 GMT</pubDate>
      <guid>http://snippets.dzone.com/posts/show/525</guid>
      <author>jmoses (jon)</author>
    </item>
  </channel>
</rss>
