Rails中的多个查询条件 - 如果存在的话.

jon*_*jon 5 activerecord ruby-on-rails multiple-conditions conditional-statements

我在这里搜索时发现了一些类似的问题,但是当我试图添加除非我找到的解决方案时,事情开始破裂......

这就是我的工作原理:

控制器:

    @metrics = Metric.where("current_ratio > ?", @screen.current_ratio_min) unless @screen.current_ratio_min.nil?
Run Code Online (Sandbox Code Playgroud)

一旦我添加另一个.where行(我需要添加很多),

    @metrics = Metric.where("current_ratio > ?", @screen.current_ratio_min) unless @screen.current_ratio_min.nil?
    .where("current_ratio < ?", @screen.current_ratio_max) unless @screen.current_ratio_max.nil?
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:

undefined method `where' for false:FalseClass
Run Code Online (Sandbox Code Playgroud)

我假设这是因为第一个除非结束我的查询.除非仅针对每个条件,我如何申请?如果是,其实问题是:

提前致谢!

Joe*_*der 7

@metrics = Metric.all
@metrics = @metrics.where('current_ratio > ?', @screen.current_ration_min) if @screen.current_ratio_min.present?
@metrics = @metrics.where('other_value > ?', @screen.other_value) if @screen.other_value.present?
Run Code Online (Sandbox Code Playgroud)

这是我能想到的最好的方法,无需以编程方式构建一个where子句字符串,这可能会导致SQL注入风险.

继续添加任意数量的条件.值得注意的是,使用if.present?而不是你的除非something.nil?

此外,Metric.all可能不是理想的,但无论你需要什么来开始所有记录.

  • 这只适用于rails 4,在rails 3中都执行查询并返回一个数组(你可以在rails 3中使用`scoped`) (3认同)