Rails where 条件为零值 [英] Rails where condition with nil value

查看:64
本文介绍了Rails where 条件为零值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现使用 where 和符号 :my_id => nil 并使用老式的?是不同的.谁能解释一下为什么?

I found out that using where with symbol :my_id => nil and using old school one with ? is different. Could anyone explain me why?

MyTable.where("my_id = ? ", nil).first
SELECT `my_tables`.* FROM `my_tables` WHERE (my_id = NULL ) LIMIT 1

没有得到任何数据

MyTable.where(:my_id => nil).first
SELECT `my_tables`.* FROM `my_tables` WHERE (`my_tables`.`my_id` IS NULL) LIMIT 1

获取 my_id 为空的数据.

Get data which has my_id is null.

在 Rails 中使用的最佳实践是什么?

What is the best practise to use in rails?

我想我没有说清楚我的问题.在我的 rails 应用程序中,请求参数为零.现有编码是 MyTable.where(:my_id => params[:id]).first在表中,有很多记录的 my_id 为空.因此,表中的第一条记录被无意识地拾取.首先,是的,是表中数据不干净的问题.

I think I didn't make clear about my question. In my rails application, request parameter is nil. Existing coding is MyTable.where(:my_id => params[:id]).first In table, there are lots of records which have my_id is null. Therefore, the first record from table is pick up without realizing. First of all, yes it is the problem with unclean data in table.

为了解决这个问题.我找到了两个解决方案

To solve this problem. I find two solutions

解决方案 1

if params[:id].present?
  MyTable.where(:my_id => params[:id]).first
end

解决方案 2

MyTable.where("my_id = ? ", nil).first

如您所知,如果我们放入(如果条件越来越多),我们的应用程序会变慢,并且不会是函数式编程.当我尝试解决方案 2 时,我感到很惊讶,因为我期望它应该给出相同的结果.

As you know, if we put (if condition more and more), our application will get slower and it will not be functional programming. When I try solution 2, I get surprised because I am expecting it should give same result.

推荐答案

正确的 SQL 语法是 my_id IS NULL,因此如果您将第一个代码段更改为以下内容,将会em> 工作:

The correct SQL syntax is my_id IS NULL, so if you change your first snippet to the following it will work:

MyTable.where("my_id IS ?", nil).first

两种语法都很好.这取决于你自己的喜好.但是,如果它是一个参数并且你不知道它是否会nil,你最好使用:

Both syntaxes are perfectly fine. It's up to your own preference. However, if it's a parameter and you don't know whether it will be nil or not, you'd better use:

MyTable.where(:my_id => parameter).first

这篇关于Rails where 条件为零值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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