I was brainstorming today about a smooth way to define conditions in an
sql query, when the numbers of attributes increase, so does the
So instead of passing a hash, I thought you could specify the conditions
directly in code.
I hacked together some example code which actually turned out to work.
The result is concise and pretty beutiful.
Ad.find(:all) do |conditions|
conditions.area_id = params[:area_id] if params[:area_id] &&
params[:area_id].to_i > 0
conditions.kind = params[:kind] if params[:kind]
conditions.selling = params[:selling] || 1
conditions.approved > 1
conditions.or do |conditions|
if params[:category_id] && params[:category_id] > 0
conditions.category_id = params[:category_id]
conditions.parent_id = params[:category_id]
p(search( :area_id => 0, :kind => ‘f’, :category_id => 13))
=> "ads.kind = ‘f’ AND ads.selling = ‘1’ AND ads.approved > 1 AND
ads.year IN (2004,2005) AND (ads.category_id = ‘13’ OR ads.parent_id =
I’m wondering if anyone is interested since I like it very much, and
be happy to see this in rails.