Martin
Martin

Reputation: 11336

In ActiveRecord, how to check if an object property is nil?

Suppose I need to check if a certain property is not set.

I imagine something like this but It doesn't work.

@users = User.find_all_by_role(["role = ?",nil])

I tried some other variants with no luck.

I guess this should be pretty straightforward.

Thank you!

Upvotes: 1

Views: 788

Answers (3)

dodecaphonic
dodecaphonic

Reputation: 459

Using ActiveRecord's pre-3.0 syntax:

@users = User.find(:all, :conditions => { :role => nil })

After 3.0 you can write:

@users = User.where(:role => nil)

Upvotes: 1

idlefingers
idlefingers

Reputation: 32067

@users = User.where(:roles => nil).all

There's no need to break into SQL for this.

Upvotes: 0

Paul Lynch
Paul Lynch

Reputation: 1337

Try: @users = User.find(:all, :conditions=>'role is null')

Upvotes: 0

Related Questions