Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete all records from all tables in database using seeds.rb

Right now my approach is to list every table one at a time and call .delete_all on it. Which is repetitive:

Example:

#app/db/seeds.rb

Blog.delete_all
Person.delete_all
Post.delete_all
User.delete_all
Author.delete_all
Book.delete_all
# ... on and on for all the tables

And then of course run rake db:seed which would clear out all the records for those above tables.

Is there a command that does exactly what I want:

  • deletes all the records from all the tables without deleting the tables themselves?

Or, is there a way to iterate through all my tables and .delete_all on each table?

like image 296
Neil Avatar asked Dec 02 '22 16:12

Neil


1 Answers

Is there a command that does exactly what I want: deletes all the records from all the tables?

bundle exec rake db:reset

This is functionally equivalent to rake db:drop db:setup.

Don't want delete the tables?

#app/db/seeds.rb
[Blog, Person, Post, User, Author, Book].each do |table|
  ActiveRecord::Base.connection.execute("TRUNCATE #{table.table_name}")
end

SQL-TRUNCATE

like image 195
Philidor Avatar answered May 26 '23 17:05

Philidor