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
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
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
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 could list all the models in the seed-file (seeds.rb), and simply run
rake db:seed
The seed file would then look something like this:
Model1.delete_all
Model2.delete_all
Model3.delete_all
Model4.delete_all
Model5.delete_all
Model6.delete_all
Model7.delete_all
...
rake db:reset
is too much for your job here. That will completely kill off your database and rebuild it from scratch, running all migrations etc. To run the seed command is faster.
# fast truncation of all tables that need truncations (select is 10x faster then truncate)
# http://grosser.it/2012/07/03/rubyactiverecord-fastest-way-to-truncate-test-database/
def truncate_all_tables
connection = ActiveRecord::Base.connection
connection.disable_referential_integrity do
connection.tables.each do |table_name|
next if connection.select_value("SELECT count(*) FROM #{table_name}") == 0
connection.execute("TRUNCATE TABLE #{table_name}")
end
end
end
If you want to delete only the data without touching the tables while using it inside your application or rails console :
Rails.application.eager_load!
ActiveRecord::Base.connection.disable_referential_integrity do
ApplicationRecord.descendants.each do |model|
model.delete_all
end
end
With this code, you don't have to bother with referencing manually your models and/or with foreign key constraints (thanks to disable_referential_integrity).
ApplicationRecord.descendants returns only true application models unlike ActiveRecord::Base.descendants (no more ApplicationRecord, schema_migrations and ar_internal_metadata).