简体   繁体   中英

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

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.

也许,尝试找到任何Profile对象:

Profile.first.nil?

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?

You can also try

Profile.first.present?

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

Try using

Profile.exists?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM