开发者

Empty database in rails

What is the best way to test for an empty database in rails? I generated a model chard开发者_如何学Cata and the controller, Chardatum. I want to loop through the database and extract a certain column, but I need a way to test if the database is empty first.


If you are fetching some Chardata allready you could do:

@chardata.any?


It depends on two things.

What kind of database are you using? And by empty, do you mean the tables have not been created yet? or just that data has not been inserted yet in to the tables?

To see if the chardatas table has no rows before proceeding:

Chardata.count.zero?

Assuming you're using MySQL, you can use the following command to see if tables have been created already in your database

Chardata.count_by_sql "SELECT COUNT(DISTINCT 'table_name') FROM 'information_schema'.'columns' WHERE 'table_schema' = 'your_db_name'".zero?


You can also check if the table has been created with CharDatum.table_exists?.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜