Rails where 条件使用 NOT NIL [英] Rails where condition using NOT NIL
问题描述
使用 rails 3 样式我将如何写相反的内容:
Using the rails 3 style how would I write the opposite of:
Foo.includes(:bar).where(:bars=>{:id=>nil})
我想找到 id 不是 nil 的地方.我试过了:
I want to find where id is NOT nil. I tried:
Foo.includes(:bar).where(:bars=>{:id=>!nil}).to_sql
但这会返回:
=> "SELECT \"foos\".* FROM \"foos\" WHERE (\"bars\".\"id\" = 1)"
这绝对不是我需要的,而且几乎看起来像是 ARel 中的一个错误.
That's definitely not what I need, and almost seems like a bug in ARel.
推荐答案
Rails 3 的规范方法:
The canonical way to do this with Rails 3:
Foo.includes(:bar).where("bars.id IS NOT NULL")
ActiveRecord 4.0 及更高版本添加了 where.not
所以你可以这样做:
ActiveRecord 4.0 and above adds where.not
so you can do this:
Foo.includes(:bar).where.not('bars.id' => nil)
Foo.includes(:bar).where.not(bars: { id: nil })
处理表之间的范围时,我更喜欢利用 merge
以便我可以更轻松地使用现有范围.
When working with scopes between tables, I prefer to leverage merge
so that I can use existing scopes more easily.
Foo.includes(:bar).merge(Bar.where.not(id: nil))
此外,由于 includes
并不总是选择连接策略,您应该使用 references
也在这里,否则你可能会得到无效的 SQL.
Also, since includes
does not always choose a join strategy, you should use references
here as well, otherwise you may end up with invalid SQL.
Foo.includes(:bar)
.references(:bar)
.merge(Bar.where.not(id: nil))
这篇关于Rails where 条件使用 NOT NIL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!