Finding records with some attribute set to nil


#1

Hi!

Suppose there is boolean attribute “has_been_read” on Posts table… how
do I find all the records that have this attribute set to NULL ?

This seems logical, but it doesn’t work (I tried other things as well):

Post.find(:all, :conditions => ["has_been_read = ?, nil])

Thank you!

David


#2

D. Krmpotic wrote:

Post.find(:all, :conditions => ["has_been_read = ?, nil])

Post.find(:all, :conditions => [“has_been_read IS NULL”])

That will work.

Unless you’re keeping some other kind of data in that column, though,
you might prefer use a migration to change it to boolean, default false:

change_column :<table_name>, :has_been_read, :boolean, :default => false

This way, you can say

Post.find(:all, :conditions => ["has_been_read = ?, false])

And in your model, put something like

def mark_as_read
self.update_attribute(‘has_been_read’, true)
end

Then you just call @thing.mark_as_read when it’s read, and you should
have everything you need.

–Al Evans


#3

thank you for responding with great answer.

Thank you for the recommendations as well… I intend to do all that… I
realized that allowing nulls in boolean column is bad…

thank you again!

david

Al Evans wrote:

D. Krmpotic wrote:

Post.find(:all, :conditions => ["has_been_read = ?, nil])

Post.find(:all, :conditions => [“has_been_read IS NULL”])

That will work.

Unless you’re keeping some other kind of data in that column, though,
you might prefer use a migration to change it to boolean, default false:

change_column :<table_name>, :has_been_read, :boolean, :default => false

This way, you can say

Post.find(:all, :conditions => ["has_been_read = ?, false])

And in your model, put something like

def mark_as_read
self.update_attribute(‘has_been_read’, true)
end

Then you just call @thing.mark_as_read when it’s read, and you should
have everything you need.

–Al Evans