Building the SQL WHERE clause dynamically, revisited
In Building the SQL WHERE clause dynamically in Rails, I showed how to build the WHERE clause like this:
1 2 3 4 5 6 7 8 9 10 11 |
class SearchController < ApplicationController def search conditions = ['1=1'] conditions << 'cond1 = :cond1' if params[:cond1] conditions << 'cond2 = :cond2' if params[:cond2] @results = Model.find(:all, :conditions => [conditions.join(' AND '), params]) end end |
Cond module to make that even easier:
1 2 3 4 5 6 7 8 9 10 11 |
class SearchController < ApplicationController def search conditions = Cond::create do cond1 '=', params[:cond1] cond2 '=', params[:cond2] end @results = Model.find(:all, :conditions => conditions) end 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 ?