mysql - Active Record NOT IN queries 和 NULL with MySQL

标签 mysql ruby-on-rails ruby-on-rails-3 activerecord rails-activerecord

我有这样的查询:

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 = NULLx != 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/

相关文章:

php - mysqli PHP 通过 MySQL 中的两个数据库/表进行搜索和过滤

php - 在 magento 中应用增值税规则

ruby-on-rails - 具有基于 Web 的 UI/API 的 FTP 客户端/服务器

ruby-on-rails - 在 Rails 中设置公共(public)文件类型的内容处置?

ajax - 如何使用 Ajax 和 jQuery 在 Rails 3 中显示 Flash 错误消息?

ruby-on-rails - Spree 可以允许我在我的电子商务应用程序中包含 'Vendors' 吗?

MySQL 从 AS 中删除

php - 如果匹配查询中的 case 条件,则除以列值

ruby-on-rails - heroku restart - 这会导致数据丢失吗

ruby-on-rails - rails 3 : Why am I getting EOFError with DELETE request and no form body?