多个查询条件的Rails - 如果存在的话。 [英] Multiple query conditions in Rails - if they exist.

查看:224
本文介绍了多个查询条件的Rails - 如果存在的话。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

下面就是我的作品:

控制器:

  @metrics = Metric.where(current_ratio>?,@ screen.current_ratio_min),除非@ screen.current_ratio_min.nil?
 

在我添加其他。凡行(其中我需要添加很多),

  @metrics = Metric.where(current_ratio>?,@ screen.current_ratio_min),除非@ screen.current_ratio_min.nil?
    。凡(current_ratio<?,@ screen.current_ratio_max),除非@ screen.current_ratio_max.nil?
 

我得到一个错误:

 未定义的方法',其中'假:FalseClass
 

我假设这是因为,第一,除非是结束我的查询。我该如何申请的,除非只是为了每一个人的条件?如果是,事实上,这个问题:\

在此先感谢!

解决方案

  @metrics = Metric.all
@metrics = @ metrics.where('current_ratio>?,@ screen.current_ration_min)如果@ screen.current_ratio_min present?
@metrics = @ metrics.where('other_value>?,@ screen.other_value)如果@ screen.other_value present?
 

这是我能想到的没有编程的方式构建它可以是危险的SQL注入where子句中的字符串的最佳方式。

请只要你想添加尽可能多的条件。值得注意的,用的,如果什么东西。present?而不是你的,除非something.nil?

此外,Metric.all可能不是很理想,但无论你需要得到所有记录的开始。

I found a few similar questions while searching here, but when I tried to add unless to the solutions I found, things started to break...

Here's what I have that works:

Controller:

    @metrics = Metric.where("current_ratio > ?", @screen.current_ratio_min) unless @screen.current_ratio_min.nil?

Once I add another .where line (of which I need to add many),

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

I get an error:

undefined method `where' for false:FalseClass

I'm assuming this is because the first unless is ending my query. How do I apply an unless just to each individual condition? If that is, in fact, the problem :\

Thanks in advance!

解决方案

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

This is the best way I can think of without programmatically building a where clause string which can be risky for SQL injection.

Keep adding as many conditions as you want. Notable, use if something.present? instead of your unless something.nil?

Also, the Metric.all might not be ideal, but whatever you need to get all records to start with.

这篇关于多个查询条件的Rails - 如果存在的话。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆