【发布时间】:2014-12-09 20:21:48
【问题描述】:
也许我快疯了,或者只是需要休息一下,但在我的 Rails 控制台中 Order.where(state: nil).count 返回 1010,但 Order.where.not(state: "pending").count 返回 0... 如果订单的状态为 nil,那么它是不是“待定”,所以我希望 not(state: "pending") 返回的集合包含集合 where(state: nil)。
难道不是这样工作的吗?如果不是,arel 的工作方式是否不同?
编辑:更多信息!当我转到另一个数据库时,其中一些记录的状态不是 nil,我运行 Order.where.not(state: "pending").count 时,我得到了一堆订单,其中没有一个是“待定”,但也没有一个是 nil。 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
所以在这种情况下,我得到了状态既不是 nil 也不是“pending”的 98 条记录,并且我得到了所有状态为 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"
【问题讨论】:
-
您确定数据库中只有
NULL/'pending'值吗?以这种方式检查:Order.pluck(:state) -
很遗憾,我无法访问 rails 环境,因此无法自行测试,但请您粘贴
Order.where.not(status: "pending").to_sql和Order.where(status:nil)的值
标签: ruby-on-rails-4 arel