views:

38

answers:

2

Now i am inputting some data from a form and i have a code to search the database inputting several parameters as input conditions. Now if one the parameters is null (i.e) the field is unchecked i need to replace that parameter with something say * so that the search query is unaffected. How would i do that?

@report = Problem.find(:all, :conditions => ["problems.cause_id = ? and problems.location_id = ? and problems.device_id = ? and problems.priority_id = ?", Report.find_by_id(params[:id]).cause_id, Report.find_by_id(params[:id]).location_id, Report.find_by_id(params[:id]).device_id, Report.find_by_id(params[:id]).priority_id])
+1  A: 
rep = Report.find_by_id(params[:id])
cause = rep.cause_id ? rep.cause_id : '*'
location = rep.location_id ? rep.location_id : '*'
device = rep.device_id ? rep.device_id : '*'
priority = rep.priority_id ? rep.priority_id : '*'
@report = Problem.find(:all, 
                       :conditions => ["problems.cause_id = ? and 
                                        problems.location_id = ? and
                                        problems.device_id = ? and 
                                        problems.priority_id = ?",
                                        cause, location, 
                                        device, priority
                                       ]
                       )
Salil
Wow, that looks a lot better now, but doesn't the null problem still stand ? i.e what if rep.cause_id was null?
Prateek
They way Salil wrote it, the field is replaced by `'*'` if it is null. Taking the line `cause = rep.cause_id ? rep.cause_id : '*'` for example, this is basically a conditional syntax where `cause = rep.cause_id` if rep.cause_id exists, or `cause = '*'` if it does not. In fact he answered the question exactly as you stated it, by replacing the queries with * if they are null.
Karl
I didnt understand the working of that code, so thanks for the explanation as well as the code.
Prateek
+1  A: 

It would be better to not have that condition at all than to use *. In this case it's simple as all of your comparison operators are "=". That means you can use the hash form of conditions. Your code is also quite inefficient as you load the same report object 3 or four times. Your question about one of the params being null doesn't make sense for this reason: you just use the same param again and again. Also you set a variable called @report to be a Problem object which is confusing.

@report = Report.find_by_id(params[:id])
conditions = {:cause_id => @report.cause_id, :location_id => @report.location_id, :device_id => @report.device_id, :priority_id => @report.priority_id}
conditions.delete_if{|k,v| v.blank?}
@problem = Problem.find(:all, :conditions => conditions)
Max Williams
Thanks its a really neat solution.You have helped me out before too on railsforums, so thanks again
Prateek