16

The following finder prints out IS NULL.

User.where(:id =>nil) #=> []
User Load (0.5ms)  SELECT `users`.* FROM `users` WHERE `users`.`id` IS NULL ORDER BY created_at DESC

But I couldn't find how to print out IS NOT NULL one?

millisami
  • 9,931
  • 15
  • 70
  • 112
  • 1
    Duplicate http://stackoverflow.com/questions/4252349/rail-3-where-condition-using-not-null – dee-see Aug 06 '11 at 12:26
  • This question has your answer - http://stackoverflow.com/questions/4252349/rail-3-where-condition-using-not-null – ipr101 Aug 06 '11 at 12:26

4 Answers4

26

Try User.where("id IS NOT NULL")

This should do your job

Dylan Markow
  • 123,080
  • 26
  • 284
  • 201
Wizz
  • 1,267
  • 1
  • 13
  • 20
20

The simplest, idiomatic ActiveRecord solution:

User.where.not(id: nil)
l3x
  • 30,760
  • 1
  • 55
  • 36
  • 2
    Note: Only works with 'rails >= v4.0.2'. See: http://apidock.com/rails/ActiveRecord/QueryMethods/WhereChain/not – morgents Apr 30 '15 at 12:20
5

User.where.not(id: nil) will work for rails 4.

User.where("id IS NOT NULL") will work for older versions.

Seth
  • 10,198
  • 10
  • 45
  • 68
Michael Sommer
  • 113
  • 2
  • 7
  • This is more or less the same as http://stackoverflow.com/a/27613775/38765 (though you answered first), and also doesn't work on Rails 3. – Andrew Grimm Dec 16 '15 at 00:40
0

Rails 4

you can try this

User.where("id is not NULL")

Also if you are looking to exclude particular id and include nil values following will work

User.where("id is NULL or id != 'excluded_id'")
error-404
  • 229
  • 4
  • 18