Tall Paul
Tall Paul

Reputation: 2450

Rails where not is not finding nil values

I am trying to search to see if a posts value is either false or nil.

Post.where.not(:top_card => true)

This only returns the false values. I have confirmed that if I do either of the following it returns the correct values

Post.where(:top_card => false)

or

Post.where(:top_card => nil)

Any idea how I can get the posts with either the nil and false value?

Am I using the wrong method to search?

Upvotes: 2

Views: 1168

Answers (2)

ryan2johnson9
ryan2johnson9

Reputation: 724

Post.where("top_card != ? OR top_card IS NULL")

NOTE that this will work with string fields while the accepted answer by @Vucko will not. i.e. in cases where you cannot put an exhaustive list of all options in the query.

e.g. this will work

User.where.not("status != ? OR status IS NULL", "active")

thanks to this forum

Upvotes: 1

Vucko
Vucko

Reputation: 20834

Use like Post.where(top_card: [false, nil].

Which will produce SELECT * FROM posts WHERE (posts.top_card IN (false, nil))

See more at Rails guides - Subset Conditions.

Upvotes: 3

Related Questions