也许我要疯了,或者只是需要休息一下,但在我的 Rails 控制台中Order.where(state: nil).count
回报1010
, but Order.where.not(state: "pending").count
回报0
...如果订单的状态为零,则它不是“待处理”,所以我期望返回的集合not(state: "pending")
包括该集where(state: nil)
.
Arel 不可以这样工作吗?如果不是,arel 是否有不同的工作方式?
编辑:更多信息!当我转到另一个数据库时,其中一些记录的状态不是 nil,并且我运行Order.where.not(state: "pending").count
我收到一堆订单,其中没有一个是“待处理”的,但也没有一个是零的。看起来where.not
隐式添加一个and not nil
到查询?
编辑:在绝望中,我转向了更黑暗的灵魂。
# look into another shop, that has records
o = Order.where(shop_id: 2)
# summon dread spirits
t = Order.arel_table[:state]
o.where(t.eq(nil).or(t.eq("pending").not)).count
=> 1569
o.where(t.eq(nil)).count
=> 1471
所以在这种情况下,我得到了 98 条状态既不是 nil 也不是“pending”的记录,并且我得到了所有状态为 nil 的记录。我真的很想知道为什么我不能直接说where.not("pending")
并具有相同的效果。如果我可以调用一个选项?喜欢,where.not("pending", include_nil: true)
?
编辑:按照@Filip Bartuzi 评论中的要求
Order.where.not(state: "pending").to_sql
=> "SELECT \"orders\".* FROM \"orders\" WHERE \"orders\".\"shop_id\" = 2 AND (\"orders\".\"state\" != 'pending')"
Orders.where(state: nil).to_sql
=> "SELECT \"orders\".* FROM \"orders\" WHERE \"orders\".\"shop_id\" = 2 AND \"orders\".\"state\" IS NULL"