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 ?
blog comments powered by Disqus