Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

activerecord search conditions - looking for null or false

When doing a search in active record I'm looking for record's that do not have an archived bit set to true.

Some of the archived bits are null (which are not archived) others have archived set to false.

Obviously,

Project.all(:conditions => {:archived => false})

misses the projects with the archived bits with null values. How can all non-archived projects be selected wtih active record?

like image 648
Daniel Avatar asked Sep 26 '09 15:09

Daniel


3 Answers

Rails 4 (possibly earlier) supports:

Project.where(archived: [false, nil])

... which is quite concise.

like image 72
TJChambers Avatar answered Oct 04 '22 16:10

TJChambers


Try this (in Rails 2):

Project.all(:conditions => ['archived IS NULL OR archived = ?', false])

This is a limitation of older versions of Rails, as explained here: https://rails.lighthouseapp.com/projects/8994/tickets/1181-ar-find-producing-null-when-it-should-be-is-null

like image 37
Ron DeVera Avatar answered Oct 04 '22 18:10

Ron DeVera


The proper database agnostic way to do this is:

Project.where("archived IS NULL OR archived = ?", false)
like image 23
sean_j_roberts Avatar answered Oct 04 '22 17:10

sean_j_roberts