views:

450

answers:

5

So I can do Post.delete_all to delete all my posts, but what if I want to delete all posts, comments, blogs, etc. I.e., how do I iterate over all my models and run the delete_all method?

+2  A: 
rake db:reset

:) It recreates your table from migrations

Vlad Zloteanu
Nice, though I'd prefer a method that doesn't require dropping and re-creating all the tables.
Horace Loeb
A: 

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

Ranchersam
A: 

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.send(:subclasses).each do |klass|
      klass.delete_all
    end
  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.

James A. Rosen
+1  A: 

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.

A: 

I know this is an old question, but I thought this might be helpful to someone. This is a very fast way of cleaning out 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 specs in an after(:all) block. This is much faster and more efficient than any of the Rails rake tasks for purging, migrating, reseting the database.

BTW: I'm pretty sure this would likely fail if you were enforcing foreign key constraints on the database side.

Sean McCleary