This article is obsolete. You may find it’s replacement at Building the SQL WHERE Clause Dynamically – updated

In Building the SQL WHERE clause dynamically in Rails, I showed how to build the WHERE clause like this:

 1 class SearchController < ApplicationController
 2   def search
 3     conditions = ['1=1']
 4 
 5     conditions << 'cond1 = :cond1' if params[:cond1]
 6     conditions << 'cond2 = :cond2' if params[:cond2]
 7 
 8     @results = Model.find(:all,
 9         :conditions => [conditions.join(' AND '), params])
10   end
11 end

Ezra Zygmuntowicz of brainsp.at fame created a Cond module to make that even easier:

 1 class SearchController < ApplicationController
 2   def search
 3     conditions = Cond::create do
 4       cond1 '=', params[:cond1]
 5       cond2 '=', params[:cond2]
 6     end
 7 
 8     @results = Model.find(:all,
 9         :conditions => conditions)
10   end
11 end

See Build AR::Base.find’s :conditions clause dynamically take one for the full source code.

Now, if that were turned into a plugin, wouldn’t that be nice ?

Search

Your Host

A picture of me

I am François Beausoleil, a Ruby on Rails and Scala developer. During the day, I work on Seevibes, a platform to measure social interactions related to TV shows. At night, I am interested many things. Read my biography.

Top Tags

Books I read and recommend

Links

Projects I work on

Projects I worked on