Question: ❓❓❓


Using the rails 3 style how would I write the opposite of:

Foo.includes(:bar).where(:bars=>{:id=>nil})

I want to find where id is NOT null. I tried:

Foo.includes(:bar).where(:bars=>{:id=>!nil}).to_sql

But that returns:

=> "SELECT     \"foos\".* FROM       \"foos\"  WHERE  (\"bars\".\"id\" = 1)"

That’s definitely not what I need, and almost seems like a bug in ARel.


Good Answer: 👌👌👌

The canonical way to do this with Rails 3:

Foo.includes(:bar).where("bars.id IS NOT NULL")

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 })

I no longer recommend using Squeel for this as it doesn’t always have a full-time maintainer, and it depends on private APIs that cause frequent breaking changes.


Read More: 👉 https://stackoverflow.com/questions/4252349/rails-where-condition-using-not-null