Forum: Ruby on Rails Finding records with some attribute set to nil

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
4057d36ea1505c263efbdbdc0bf511cd?d=identicon&s=25 D. Krmpotic (rubypassion)
on 2007-03-17 20:12
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
807e34b31d5463a9ac05d41458a9e537?d=identicon&s=25 Al Evans (al-evans)
on 2007-03-17 22:30
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
4057d36ea1505c263efbdbdc0bf511cd?d=identicon&s=25 D. Krmpotic (rubypassion)
on 2007-03-17 22:59
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
This topic is locked and can not be replied to.