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

My approach now is to list each table one at a time and name .delete_allit. What is repeated:

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:seedthat will clear all records for the tables above.

Is there a team that does exactly what I want:

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

Or is there a way to iterate through all of my tables and .delete_allin each table?

+4
source share
5 answers

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

bundle exec rake db:reset

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

Don't want to delete 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

+7

, . , : ActiveRecord::Base.connection.tables, .

puts ActiveRecord::Base.connection.tables                                       

ActiveRecord::Base.connection.tables.each do |table|                            
  next if table.match(/\Aschema_migrations\Z/)                                  
  klass = table.singularize.camelize.constantize                                
  klass.delete_all                                                              
end

Edit:

id 1, create , destroy .

ActiveRecord::Migration.drop_table(:users)
ActiveRecord::Migration.create_table(:users)

, User, id 1. , drop_table create_table , , , , User. , :

User.table_name # it will give you "users"
# in above code, you can do:
ActiveRecord::Migration.drop_table(klass.table_name) 
# string and symbol: both type of arguments work here!
+5

ruby- , ObjectSpace , , ActiveRecord:: Base

models = ObjectSpace.each_object(Class).select { |klass| klass < ActiveRecord::Base }
models.each{|m|m.delete_all}

, rake, seeds.rb, , .

+4

,

Rails.application.eager_load!

# This only gets direct subclasses, since we are just deleting
# No reason to get their subclasses
models = ActiveRecord::Base.subclasses

models.each(&:delete_all)
+1

seeds.rb. , / ( __).

Rails.application.eager_load!
ActiveRecord::Base.connection.disable_referential_integrity do
  ApplicationRecord.descendants.each do |model|
    model.delete_all
  end
end

NB: ApplicationRecord.descendants , ActiveRecord:: Base.descendants( ApplicationRecord, schema_migrations ar_internal_metadata).

0

All Articles