How to delete all data from all tables in Rails?

Viewed 74627

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?

17 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.

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

If you're trying to do this from code instead of the command line, say from a Test::Unit::TestCase#teardown method, you could 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, though: neither is particularly fast. You're definitely better off with transactional tests if you can.

In Rails 6, you can do rails db:truncate_all to remove all data without dropping any tables.

If you would like to seed your db after that, you could also do rails db:seed:replant to truncate all data and seed database

Building up on @Vlad Zloteanu's answer, here is a version to remove all tables while keeping the user records and login sessions together with some meta information. Feel free to adjust the list of tables to 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

If you want to delete all the tables and re-initialize with default values you can use.

rails db:bootstrap
Related