Martin
Martin

Reputation: 11336

ActiveRecord, how to select empty fields

I'm trying to count all User with empty last_name.

I'm trying those but they don't work

User.where("last_name = ?", "").count
User.where("last_name = ?", nil).count

Calling all against nil works but I still need to select those who's last_name are empty.

User.where("last_name != ?", nil).count

Upvotes: 0

Views: 635

Answers (2)

tokland
tokland

Reputation: 67880

User.where(:last_name => nil).count

Or using ARel:

User.where(User.arel_table[:last_name] == nil).count

Upvotes: 6

pguardiario
pguardiario

Reputation: 54984

For mysql maybe:

User.where("last_name is null").count

otherwise maybe:

User.find_all_by_last_name(nil).count

Upvotes: 1

Related Questions