Big_Bird
Big_Bird

Reputation: 427

How do I count nil values in a model?

Assuming I have a model named "Person" & that person is defined by name, age, gender & race.

How do I iterate through the model to find out which values are nil?

For example:

name: peter

age: 34

gender: nil

race: nil

--Nil count: 2--

I understand I would have iterate through each field, do a +1 if value if nil & output the total value.

Thanks for any help or guidance!

Upvotes: 0

Views: 1357

Answers (1)

mu is too short
mu is too short

Reputation: 434685

If your instance is p then:

nils = p.attributes.values.select(&:nil?).count

will give you the number of nil attributes.

Upvotes: 9

Related Questions