Search code examples
ruby-on-railsrubysqueel

Using NOT operator with Squeel?


How do I write a SQL query using Squeel?

    SELECT * FROM documents where (NOT document.deleted OR document.deleted IS NULL)

I tried:

    Document.where { (-deleted) | (deleted == nil) }

but get this error:

    NoMethodError: undefined method `|' for deleted.-@:Squeel::Nodes::KeyPath

Solution

  • It's very important to notice that ActiveRecord stores boolean values as string flags in the database. Therefore, in the case you mentioned, document.deleted equals 'f' which is a truthy value. That's why you can't simply use the NOT operator.

    Perhaps what you're looking for is:

    Document.where { deleted.eq(false) | deleted.eq(nil) }
    

    Cheers