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
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") }