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 to delete_all over all my models and run the delete_all method?

+60
ruby-on-rails activerecord
Jul 28 '09 at 19:14
source share
16 answers
 rake db:reset 

He recreates the table from the migrations.

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

 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 

Answer copied from: answer to SO .

+81
Jul 28 '09 at 19:21
source share

You can have finer control with:

 rake db:drop:all 

And then create the database without performing the migration,

 rake db:create:all 

Then run all your migrations,

 rake db:migrate 

You can also do:

 mysqladmin drop databasename 
+28
Jul 28 '09 at 23:05
source share

If you are trying to do this from code instead of the command line, say, from the Test::Unit::TestCase#teardown , you can do either

 class MyTest < Test::Unit::TestCase def teardown ActiveRecord::Base.subclasses.each(&:delete_all) end end 

or

 class MyTest < Test::Unit::TestCase def teardown Rake::Task['db:reset'].invoke end end 

I warn you: although not very fast. You are certainly better off conducting transactional tests.

+23
Jul 28 '09 at 23:11
source share

If you just want to start a new job with a new set of empty tables, you can first make sure that you have a modern schema definition in db / schema.rb:

 rake db:schema:dump 

and then:

 rake db:schema:load 

which has the effect of dropping tables and then re-creating them without using your entire migration battery.

+17
May 7 '10 at 2:59
source share

A faster way to simply delete table rows is to use the TRUNCATE command.

Many other answers seem to ignore the difference between deleting rows and rolling back the table. Deleting a table destroys table data and schema; that you need to take additional steps to recreate the tables. Sean McLeary's answer was the best I've seen, so I used it as a starting point. However, I think it is better to use the TRUNCATE command, because it should be faster, and also resets keys with auto-increment. Also, using map instead of each shortens the code a bit.

 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 
+10
Jun 13 '11 at 15:00
source share

rails db:purge

was recently added to ActiveRecord in the main rail branch 4.2.0.alpha

https://github.com/rails/rails/commit/e2f232aba15937a4b9d14bd91e0392c6d55be58d

+10
Aug 05 '14 at 12:58
source share

You can list all the models in the seed file (seeds.rb) and just run

 rake db:seed 

Then the seed file will look something like this:

 Model1.delete_all Model2.delete_all Model3.delete_all Model4.delete_all Model5.delete_all Model6.delete_all Model7.delete_all 

...

rake db:reset too much for your work here. This will completely destroy your database and rebuild it from scratch, doing all the migrations, etc. To run the seed command faster.

+4
Jul 06 '12 at 19:40
source share

Accepted answer with Postgres db:

 namespace :db do desc "Truncate all tables" task :truncate => :environment do conn = ActiveRecord::Base.connection postgres = "SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname='public'" tables = conn.execute(postgres).map { |r| r['tablename'] } tables.delete "schema_migrations" tables.each { |t| conn.execute("TRUNCATE \"#{t}\"") } end end 
+4
Jun 19 '13 at 4:31 on
source share

This will work for Rails 4.

 (ActiveRecord::Base.connection.tables - ['schema_migrations']).each do |table| table.classify.constantize.destroy_all end 
+4
Dec 21 '13 at 1:58
source share

If you want to delete only data without touching the tables, using it inside your application or rails console:

 Rails.application.eager_load! ActiveRecord::Base.connection.disable_referential_integrity do ApplicationRecord.descendants.each do |model| model.delete_all end end 

With this code, you donโ€™t have to worry about manually referencing your models and / or with foreign key constraints (due to disabling integration_refractivity).
ApplicationRecord.descendants returns only true application models, unlike ActiveRecord :: Base.descendants (no more than ApplicationRecord, schema_migrations and ar_internal_metadata).

+4
Mar 08 '17 at 9:41 on
source share

We lost our place in Stack Overflow without mentioning the database_cleaner gem :

Database Cleaner is a set of strategies for cleaning your database in Ruby. The initial use was to ensure a clean state during testing. Each strategy is a small code, but it is the code that is usually required in any ruby โ€‹โ€‹application that tests the database.

According to the โ€œstrategyโ€, Mr. Maby means: truncation, transaction and deletion.

ActiveRecord, DataMapper, Sequel, MongoMapper, Mongoid and CouchPotato are supported.

The following is a snippet of code from "Cleaning the README Database" :

 require 'database_cleaner' DatabaseCleaner.strategy = :truncation # then, whenever you need to clean the DB DatabaseCleaner.clean 
+3
Jun 25 '12 at 20:18
source share
 # fast truncation of all tables that need truncations (select is 10x faster then truncate) # http://grosser.it/2012/07/03/rubyactiverecord-fastest-way-to-truncate-test-database/ def truncate_all_tables connection = ActiveRecord::Base.connection connection.disable_referential_integrity do connection.tables.each do |table_name| next if connection.select_value("SELECT count(*) FROM #{table_name}") == 0 connection.execute("TRUNCATE TABLE #{table_name}") end end end 
+3
Jul 03 '12 at 16:15
source share

I know this is an old question, but I thought it might help someone. This is a very quick way to clear all data from a database.

 tables = [] ActiveRecord::Base.connection.execute("show tables").each { |r| tables << r[0] } tables = tables - ["schema_migrations"] tables.each do |table| ActiveRecord::Base.connection.execute("DELETE FROM #{table} WHERE 1 = 1") end 

I use this technique in certain specifications in the after(:all) block. This is much faster and more effective than any of the Rake Rake tasks for cleaning, migrating, reselling the database.

BTW: I am sure this will most likely fail if you apply foreign key constraints on the database side.

+2
Jun 10 2018-10-10T00:
source share

My 50 cents for cleaning db and the ability to start the migration again (in cases where you cannot delete the database, for example AWS RDS):

 # get connection conn = ActiveRecord::Base.connection # find all tables needed to be removed tables = conn.execute("SELECT * FROM pg_catalog.pg_tables WHERE schemaname='public' AND tablename<>'schema_migrations'").to_a.map { |r| r['tablename'] } # remove all tables except schema_migrations tables.each { |t| conn.execute("DROP TABLE #{t}") } # clean migrations table conn.execute("TRUNCATE TABLE schema_migrations") 

And now you can run rake db:migrate so that your db is in a clean state.

+1
Mar 08 '16 at 21:26
source share

In Rails 6, you can do rails db:truncate_all to delete all data without deleting the tables.

If after that you want to populate your database, you can also do rails db:seed:replant to truncate all the data and the database.

+1
Aug 21 '19 at 8:12
source share

Based on @Vlad Zloteanu's answer, here is a version for deleting all tables, saving user records and login sessions along with some meta-information. Feel free to customize the list of tables to suit your requirements.

 # lib/tasks/db/truncate.rake namespace :db do desc 'Truncate all tables except users state and meta' task truncate: :environment do conn = ActiveRecord::Base.connection tables = conn.tables - %w[ sessions users roles users_roles schema_migrations ar_internal_metadata ] tables.each { |t| conn.execute("TRUNCATE #{t}") } puts "Truncated tables\n================\n#{tables.sort.join("\n")}" end end 
0
May 17 '18 at 15:28
source share



All Articles