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
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.
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
If there are foreign_key
error like ActiveRecord::StatementInvalid (PG::FeatureNotSupported: ERROR: cannot truncate a table referenced in a foreign key constraint)
Then, CASCADE option would help.
tables.each { |t| conn.execute("TRUNCATE \"#{t}\" CASCADE") }
rails db:purge
has recently been added to ActiveRecord in the master branch of rails 4.2.0.alpha
https://github.com/rails/rails/commit/e2f232aba15937a4b9d14bd91e0392c6d55be58d
My 50 cents, for cleaning db and able to run migrations again (in cases when you can't delete database, eg 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
to have your db in a clean state.