<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet href="/stylesheets/rss.css" type="text/css"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
  <channel>
    <title>&amp;lt;blog&amp;gt;Matt Osentoski&amp;lt;/blog&amp;gt;: Tag ActiveRecord</title>
    <link>http://matt.osentoski.com/articles/tag/activerecord?tag=activerecord</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description></description>
    <item>
      <title>Creating dynamic WHERE clauses with ActiveRecord</title>
      <description>Hibernate has a class called Criteria that's used to help eliminate the logic in dynamic queries.  I was building a Ruby on Rails application recently and wanted similar functionality, but didn't see the equivalent of a Criteria object in ActiveRecord.   I searched around for a 3rd party library and found a few, but wasn't interested in a heavy API.  So, I rolled my own Class to create dynamic WHERE clauses.
&lt;br /&gt;
&lt;br /&gt;
The class is called SqlBuilder and works on the principle that the ActiveRecord find() method can accept a String and Hash of parameters in the :conditions clause.  What my class does is create the SQL string, inserting symbols in place of values.
&lt;br /&gt;
&lt;br /&gt;
To use my class in your own code, grab the sql_builder.rb file &lt;a href="/files/sql_builder.rb"&gt;here&lt;/a&gt; and follow the sample code below:
&lt;br /&gt;&lt;br /&gt;
&lt;div class="typocode"&gt;&lt;pre&gt;&lt;code class="typocode_default "&gt;&lt;notextile&gt;require 'sql_builder'
 
builder = SqlBuilder.new
builder.where_helper('division', params['division'], 'divisions.id')
builder.where_helper('vehicle', params['vehicles'], 'vehicles.id')
builder.where_helper('notes', params['notes'].strip, 'claims.notes', 'AND', 'LIKE')
sql_conditions, sql_conditions_hash = builder.get_sql_conditions()

@claims = Claim.find(:all, :include =&amp;gt; [:divisions, :vehicles],
 :conditions =&amp;gt; [sql_conditions, sql_conditions_hash])&lt;/notextile&gt;&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;
&lt;br /&gt;&lt;br /&gt;
&lt;strong&gt;Disclaimer:&lt;/strong&gt;
This is a very, very simple Class and probably won't work for every scenerio.  If you have very complex needs you should check out some of the other libraries, that are out there.</description>
      <pubDate>Wed, 24 Jan 2007 14:58:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:0c729aa1-8bf3-498b-94e0-a991519edf2c</guid>
      <author>Matt Osentoski</author>
      <link>http://matt.osentoski.com/articles/2007/01/24/creating-dynamic-where-clauses-in-active-record</link>
      <category>Rails</category>
      <category>Rails</category>
      <category>ActiveRecord</category>
      <enclosure length="4175" type="application/octet-stream" url="http://matt.osentoski.com/files/sql_builder.rb"/>
    </item>
  </channel>
</rss>
