Mat*_*ngh 3 activerecord ruby-on-rails
这个问题基于 活动记录 where 方法而不是
Item.where("color != ?", 'red'),或.where.not不返回 nil 值的模拟。我如何查询以包括这些?
根本问题是 SQL 数据库如何与 NULL 进行比较,而不是 Rails 或 ActiveRecord 如何工作。如果您想要颜色为 NULL 的记录,则必须使用类似where color IS NULL. NULL 不被视为“非红色”。最终,为了得到你想要的东西,你需要or在 SQL 中覆盖这两种情况。
在 ActiveRecord 中,您需要这样:
Item.where("color != ? or color is null", 'red')
Run Code Online (Sandbox Code Playgroud)
你也可以这样做:
Item.where("color != ?", 'red').or(Item.where(color: nil))
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1148 次 |
| 最近记录: |