Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
活动记录不在查询中,MySQL为空_Mysql_Ruby On Rails_Ruby On Rails 3_Activerecord_Rails Activerecord - Fatal编程技术网

活动记录不在查询中,MySQL为空

活动记录不在查询中,MySQL为空,mysql,ruby-on-rails,ruby-on-rails-3,activerecord,rails-activerecord,Mysql,Ruby On Rails,Ruby On Rails 3,Activerecord,Rails Activerecord,我有一个类似这样的问题: Tag.where('id not IN (?)', current_user.tags.pluck(:id)).uniq 什么时候 返回NULL,我从标记查询中没有得到任何结果,这不是期望的行为 我做错了什么 谢谢。我不认为当前用户.tags.pluck(:id)返回的是一个nil,它返回的是一个空数组。在这方面。结果是一些荒谬的SQL,如下所示: select tags.* from tags where id in (null) tag_ids = curre

我有一个类似这样的问题:

Tag.where('id not IN (?)', current_user.tags.pluck(:id)).uniq
什么时候

返回NULL,我从标记查询中没有得到任何结果,这不是期望的行为

我做错了什么


谢谢。

我不认为
当前用户.tags.pluck(:id)
返回的是一个
nil
,它返回的是一个空数组。在这方面。结果是一些荒谬的SQL,如下所示:

select tags.* from tags where id in (null)
tag_ids = current_user.tags.pluck(:id)
if(tag_ids.empty?)
  tags = Tag.all
else
  tags = Tag.where('id not in (?)', tag_ids)
end
由于SQL的NULL特性(特别是
x=NULL
x!=NULL
对于所有
x
都是false),WHERE子句中的
in(NULL)
notin(NULL)
将不匹配任何内容

Rails将Ruby的
[]
转换为
NULL
是相当愚蠢的(对此进行了更多讨论),但即使它足够聪明,可以引发异常,您仍然必须手动处理“空数组”情况,如下所示:

select tags.* from tags where id in (null)
tag_ids = current_user.tags.pluck(:id)
if(tag_ids.empty?)
  tags = Tag.all
else
  tags = Tag.where('id not in (?)', tag_ids)
end
您不需要uniq中的
in
,SQL
in
操作符将其RHS视为一个集合,以便在幕后折叠重复项。

使用
where.not
让Rails处理传递的参数为空数组的情况。 正如mu太短所指出的,当传递给查询条件的值是空数组时,ActiveRecord会将其转换为
NULL
,这会弄乱您的查询并始终返回空结果

处理这个问题的老方法是有条件地检查作为参数的空数组,而不是添加这个条件。然而,Rails 4引入了
where.not
,我们不再需要这种检查

我们可以简单地做到:

Tag.where.not( id: current_user.tags.pluck(:id) ).uniq

现在ActiveRecord将自动检查空数组,当它看到它时,条件变为
1=1
,这基本上是没有意义的,但更重要的是,它只是被忽略,其余的查询将运行,就好像从未将该条件添加到查询中一样。

甚至不需要提取id:D@MikeHeft真正地Rails必须自动返回主键吗?我从来没有尝试过,可能是因为我们主要使用唯一的id,但如果它有效的话,这是非常聪明的。是的,它足够聪明,可以从对象中知道获取id。只对id列tho有效。对于任何其他专栏,你都需要勇气D@MikeHeft美女谢谢你的确认。如果您愿意,请随意编辑答案。