结合查找条件。 (导轨)

时间:2010-07-09 14:22:28

标签: sql ruby-on-rails forms

现在我从表单输入一些数据,我有一个代码来搜索输入几个参数作为输入条件的数据库。现在,如果一个参数为空(即)该字段未选中,我需要将该参数替换为*,以便搜索查询不受影响。我该怎么做?

@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])

2 个答案:

答案 0 :(得分:1)

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
                                       ]
                       )

答案 1 :(得分:1)

最好不要使用那个条件而不是使用*。在这种情况下,它很简单,因为所有的比较运算符都是“=”。这意味着您可以使用哈希形式的条件。当您加载相同的报表对象3到4次时,您的代码效率也非常低。关于其中一个参数为null的问题由于这个原因没有意义:你只是一次又一次地使用相同的参数。您还将一个名为@report的变量设置为一个令人困惑的问题对象。

@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)