Gmane
From: Rafał Komorowski <komor@...>
Subject: How to programatically build :contitions with elegance?
Newsgroups: gmane.comp.lang.ruby.rails
Date: 2005-10-31 10:43:54 GMT (3 years, 35 weeks, 2 days, 12 hours and 30 minutes ago)
Hello Railers,

I wonder how to avoid a matrix of 3x3=9 IF's when constructing  
a :conditions string for find query, when I have three independent  
sets of optional conditions.

Details: my app displays a task list. A task is associated with a  
project, a person and it also has a creation date. My Task-view has a  
set of popup-menus that trigger 3 display options:
- display tasks from projects: all, project-1, project-2, etc...
- display tasks for persons: all, person-1, person-2, etc...
- display tasks for month: all, January, February, etc...

Those popups are grouped in a form, that sends a params 
[:display_options] hash to TaskController. It works OK, the  
controller builds a DisplayOptions object from this Hash (to populate  
popups with the 'collection_select' helper). Now I try to implement a  
query that meets the conditions set by the DisplayOptions object.

If I had only one popup, this would be simple:

     if (params[:display_options] != nil)    # we've got options
       @display_options = TaskHelper::DisplayOptions.new(params 
[:display_options])    # build object for view
       @tasks = Task.find( :all, :conditions => [ "project = ?",  
@display_options["project"] ] )
       ...

But I have 3 independent popups, so a query conditions can look like  
this:
     [ "project = ? and person_id = ?",  ..... ]
or like this:
     [ "person_id = ? and month = ?",  .... ]
or any other from 3x3=9 variants, depending what options are set in  
my popups. For example if 'Projects' popup is set to 'All' then I  
don't need to include it in the query, since tasks from any project  
should be found.

Is there some more elegant way of building such a query? Some neat  
SQL statement or some neat form of 'find' method with incremental  
conditions builder?
My knowledge of SQL is only rudimentary (thanks to Rails!), but I've  
checked, that the following syntax doesn't work (at least for MySQL):
     SELECT * FROM tasks WHERE project_id=* AND person_id=3 ...
so I can't substitute '*' if popup is set to "All".

Any ideas? TIA

-- 

Rafał Komorowski
komor@...
GG: 4083718
<http://homepage.mac.com/komor/iblog/>