Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete all data from all tables in Rails?

I can do Post.delete_all to delete all my posts, but what if I want to delete all posts, comments, blogs, etc.?

How do I iterate over all my models and run the delete_all method?

like image 221
Tom Lehman Avatar asked Jul 28 '09 19:07

Tom Lehman


People also ask

What is the difference between delete and destroy in Rails?

Rails Delete operation using delete method Unlike the destroy method, with delete, you can remove a record directly from the database. Any dependencies to other records in the model are not taken into account. The method delete only deletes that one row in the database and nothing else.


2 Answers

rake db:reset  

It recreates your table from migrations.

As suggested in the comments, a faster way to do it (but you have to add a new rake task) is:

namespace :db do   desc "Truncate all tables"   task :truncate => :environment do     conn = ActiveRecord::Base.connection     tables = conn.execute("show tables").map { |r| r[0] }     tables.delete "schema_migrations"     tables.each { |t| conn.execute("TRUNCATE #{t}") }   end end 

Response copied from: answer on SO.

like image 196
Vlad Zloteanu Avatar answered Sep 19 '22 19:09

Vlad Zloteanu


You can have finer control with:

rake db:drop:all 

And then create the database without running the migrations,

rake db:create:all 

Then run all your migrations,

rake db:migrate  

You can also do:

mysqladmin drop databasename 
like image 26
Sameer C Avatar answered Sep 21 '22 19:09

Sameer C