How to delete all data from all tables in Rails?
Solution 1:
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.
Solution 2:
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
Solution 3:
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.
Solution 4:
If you simply want to start fresh with a fresh set of empty tables, you can first ensure you have an up-to-date definition of the schema 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 running through your entire battery of migrations.