我有这样的查询:
Tag.where('id not IN (?)', current_user.tags.pluck(:id)).uniq
什么时候
current_user.tags.pluck(:id)).uniq
返回 NULL,我没有从 Tag 查询中得到任何结果,这不是所需的行为。
我在这里做错了什么?
谢谢。
最佳答案
我不认为 current_user.tags.pluck(:id)
返回一个 nil
,它返回一个空数组。 ActiveRecord will treat an empty array as a NULL在这种情况下。结果是一些像这样的无意义的 SQL:
select tags.* from tags where id in (null)
由于 SQL 的 NULL 的特性(特别是 x = NULL
和 x != NULL
对于所有 x
都是假的), WHERE 子句中的 in (null)
或 not in (null)
将不匹配任何内容。
Rails 将 Ruby 的 []
转换为 NULL
是相当愚蠢的(关于 over here 的更多讨论)但即使它足够聪明以引发异常,你d 仍然需要像这样手动处理“空数组”的情况:
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
,SQL in
运算符会将其 RHS 视为一个集合,因此重复项将在幕后折叠。
关于mysql - Active Record NOT IN queries 和 NULL with MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18949471/