gpt4 book ai didi

ruby-on-rails - ActiveRecord:可以使用 .where(foo: "bar") 成功查询但是 .where.not(foo: "bar") 没有返回正确的结果

转载 作者:数据小太阳 更新时间:2023-10-29 08:58:32 26 4
gpt4 key购买 nike

我有一个这样构建的查询:

@events = current_organization.events.order(started_at: :asc)

我想查询所有那些status 不是"canceled" 的事件。但是,当我使用这样的查询时:

current_organization.events.order(started_at: :asc).where.not(status: "canceled")

它什么都不返回。但是,出于实验目的,我尝试了:

@events = current_organization.events.where(status: "canceled")

它成功返回了取消的事件。由于某种原因,逆函数不起作用。有什么原因吗?

编辑:我能找到的唯一解决办法就是使用 where(status: nil) 但这真的很不直观。

最佳答案

您问题的更新:

Edit: My only work around I can find is just using where(status: nil) but that's really unintuitive.

很重要。这告诉我你的 status列允许 NULL值(value)观,你有 NULL值(value)观。

那些NULL s 与 ActiveRecord 对 where.not 的有点糟糕的实现相结合是你麻烦的原因。如果我们查看以下生成的 SQL:

where.not(status: "canceled")

我们看到:

("events"."status" != 'canceled') 

但是在 SQL 中,x = nullx <> null两者都评估为 null对于所有 x (包括当 x 本身是 null 时)和 null在 SQL 中不是真值;这意味着x <> yx = y 不完全相反什么时候null涉及 s:如果一行的 statusnull那么where status = 'canceled'都不是也不where status != 'canceled'会找到的。

每当null涉及 s,您必须与处理 null 的运算符合作他们如你所愿:is null , is not null , is distinct from , is not distinct from , ...

允许null在你的status专栏对我来说听起来很奇怪,修复它会使问题消失:

  1. 添加迁移以更改所有 null更好的工作状态。 status is null专栏说行/模型根本没有状态,这很奇怪,所以给他们一个真实的状态代码。
  2. 添加迁移以使您的 status专栏not null这样您就不必担心 null状态。
  3. 更新模型的验证以不允许 status.nil?发生。

一般来说,不要在任何地方使用可为空的列,除非您确定 null这是有道理的,你准备好如何处理null在 SQL 中工作。

关于ruby-on-rails - ActiveRecord:可以使用 .where(foo: "bar") 成功查询但是 .where.not(foo: "bar") 没有返回正确的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42379889/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com