user4571629
user4571629

Reputation: 450

Rails check if model is empty

I created model Profile.rb
I have on the db column name, Currently it's empty
How do I check on the rails console if Profile is empty?
I have tried Profile.empty? but I guess that's not the right way

Upvotes: 11

Views: 8005

Answers (5)

thank_you
thank_you

Reputation: 11107

You can also try

Profile.first.present?

This makes the code more readable imho but nil? works too.

Upvotes: 1

kajal ojha
kajal ojha

Reputation: 1278

Try using

Profile.exists?

it will return true if the table is not empty and false if the table is empty.

Upvotes: 4

Shiva
Shiva

Reputation: 12524

This also could be an Option for you.

Profile.any?

This will make a query to DB like

Profile.any?
# (0.6ms)  SELECT COUNT(*) FROM "profiles"
# => false

This would be more semantic I guess.

Upvotes: 15

Brian Wagner
Brian Wagner

Reputation: 1110

It's not clear to me if you mean the Profile table is empty, or the name column in any one Profile entry is empty.

As mentioned by kjprice, you could just query the database for first. Or do

Profile.all.count < 1

Otherwise, I'd guess you were looking at the name column in a single Profile entry.

Profile.first.name.empty?

Upvotes: 0

kjprice
kjprice

Reputation: 1318

Maybe, try to find any Profile object:

Profile.first.nil?

Upvotes: 3

Related Questions