TRUNCATE All Tables in a Ruby on Rails Application

Update: Read the comments. There are some caveats to the following script

Frequently when I'm in the development stage of an application, I have a need to delete all the rows from all the tables in the database to end up with just the structure(a bare DB). The right thing to do is to run the TRUNCATE command on all the tables. It will delete all the data and also reset the auto increment value. But the only current way to get a bare DB in rails now is to run rake db:reset. This will run rake db:drop, rake db:create and rake db:migrate. The downside of this is that if you have a reasonable number of migrations this command can take quite some time to run which is really not efficient when you are iterating fast. Hence I have created a rake task to TRUNCATE all the tables.

Just create a file named db_truncate.rake in your lib/tasks directory with this code in it. Save the file and then run rake db:truncate. Your database now should have no data now. Before you run the task make sure that you have a valid database.yml file and have created the database tables before running this command. You should be able to run rake db:migrate without an error

This rake task works with both mysql and sqlite databases.

blog comments powered by Disqus