简体   繁体   English

Rails检查模型是否为空

[英]Rails check if model is empty

I created model Profile.rb 我创建了模型Profile.rb
I have on the db column name , Currently it's empty 我有db列name ,目前它是空的
How do I check on the rails console if Profile is empty? 如果Profile为空,如何检查rails控制台?
I have tried Profile.empty? 我试过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 这将对DB进行查询

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. 我不清楚您是否表示Profile表为空,或者任何一个Profile条目中的name列为空。

As mentioned by kjprice, you could just query the database for first. 正如kjprice所提到的,你可以先查询数据库。 Or do 或者做

Profile.all.count < 1

Otherwise, I'd guess you were looking at the name column in a single Profile entry. 否则,我猜你正在查看单个Profile条目中的name列。

Profile.first.name.empty?

You can also try 你也可以试试

Profile.first.present?

This makes the code more readable imho but nil? 这使得代码更具可读性但是nil? works too. 也有效。

Try using 尝试使用

Profile.exists?

it will return true if the table is not empty and false if the table is empty. 如果表不为空,它将返回true;如果表为空,则返回false。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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