Nice programing

Rails의 모든 테이블에서 모든 데이터를 삭제하는 방법은 무엇입니까?

nicepro 2020. 12. 2. 21:58
반응형

Rails의 모든 테이블에서 모든 데이터를 삭제하는 방법은 무엇입니까?


Post.delete_all모든 게시물을 삭제할 있지만 모든 게시물, 댓글, 블로그 등을 삭제하려면 어떻게해야합니까?

모든 모델을 반복하고 delete_all메서드를 실행하려면 어떻게해야 합니까?


rake db:reset 

마이그레이션에서 테이블을 다시 만듭니다.

의견에서 제안했듯이 더 빠른 방법은 다음과 같습니다 (하지만 새 레이크 작업을 추가해야 함).

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

에서 복사 한 응답 : SO에 대한 답변 .


다음을 통해 더 세밀하게 제어 할 수 있습니다.

rake db:drop:all

그런 다음 마이그레이션을 실행하지 않고 데이터베이스를 만듭니다.

rake db:create:all

그런 다음 모든 마이그레이션을 실행하고

rake db:migrate 

다음을 수행 할 수도 있습니다.

mysqladmin drop databasename

명령 줄 대신 코드에서이 작업을 수행하려는 경우 (예 : Test::Unit::TestCase#teardown메서드에서) 다음 중 하나를 수행 할 수 있습니다.

class MyTest < Test::Unit::TestCase

  def teardown
    ActiveRecord::Base.subclasses.each(&:delete_all)
  end

end

또는

class MyTest < Test::Unit::TestCase

  def teardown
    Rake::Task['db:reset'].invoke
  end

end

하지만 경고합니다. 둘 다 특히 빠르지 않습니다. 가능한 한 트랜잭션 테스트를 사용하는 것이 좋습니다.


새로운 빈 테이블 세트로 새로 시작하려면 먼저 db / schema.rb에 스키마의 최신 정의가 있는지 확인할 수 있습니다.

rake db:schema:dump

그리고:

rake db:schema:load

이는 전체 마이그레이션 배터리를 실행하지 않고도 테이블을 삭제 한 다음 다시 생성하는 효과가 있습니다.


에 대한 빠른 방법 바로 삭제 테이블 행이 TRUNCATE 명령을 사용하는 것입니다.

다른 많은 답변은 행 삭제와 테이블 삭제의 차이를 무시하는 것 같습니다. 테이블을 삭제하면 테이블 데이터와 스키마가 손상됩니다. 즉, 테이블을 다시 생성하려면 추가 단계가 필요합니다. Sean McLeary의 답변은 내가 본 것 중 최고 였으므로 출발점으로 사용했습니다. 그러나 TRUNCATE 명령을 사용하는 것이 더 빠르며 자동 증가 키도 재설정하기 때문에 더 좋습니다. 또한 map대신 사용 each하면 코드가 약간 단축됩니다.

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

rails db:purge

최근에 rails 4.2.0.alpha의 마스터 브랜치에서 ActiveRecord에 추가되었습니다.

https://github.com/rails/rails/commit/e2f232aba15937a4b9d14bd91e0392c6d55be58d


시드 파일 (seeds.rb)의 모든 모델을 나열하고 간단히 실행할 수 있습니다.

rake db:seed

시드 파일은 다음과 같습니다.

Model1.delete_all
Model2.delete_all
Model3.delete_all
Model4.delete_all
Model5.delete_all
Model6.delete_all
Model7.delete_all

...

rake db:reset여기서 당신의 일에 너무 많은 것입니다. 그러면 데이터베이스를 완전히 죽이고 처음부터 다시 빌드하여 모든 마이그레이션을 실행합니다. seed 명령을 실행하는 것이 더 빠릅니다.


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

이것은 Rails 4에서도 작동합니다.

(ActiveRecord::Base.connection.tables - ['schema_migrations']).each do |table|
    table.classify.constantize.destroy_all
end

애플리케이션 또는 Rails 콘솔 내에서 사용하는 동안 테이블을 건드리지 않고 데이터 만 삭제하려면 다음을 수행하십시오.

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

이 코드를 사용하면 모델을 수동으로 참조하거나 외래 키 제약 조건 (disable_referential_integrity 덕분에)을 사용하여 귀찮게 할 필요가 없습니다.
ApplicationRecord.descendants는 ActiveRecord :: Base.descendants와 달리 실제 애플리케이션 모델 만 반환합니다 (더 이상 ApplicationRecord, schema_migrations 및 ar_internal_metadata 없음).


우리는 database_cleaner gem을 언급하지 않은 것에 대해 Stack Overflow에서 사절했습니다 .

Database Cleaner is a set of strategies for cleaning your database in Ruby. The original use case was to ensure a clean state during tests. Each strategy is a small amount of code but is code that is usually needed in any ruby app that is testing with a database.

By 'strategy', Mr. Mabey means: truncation, transaction, and deletion.

ActiveRecord, DataMapper, Sequel, MongoMapper, Mongoid, and CouchPotato are supported.

Here is a quick code snippet from the Database Cleaner README:

require 'database_cleaner'
DatabaseCleaner.strategy = :truncation

# then, whenever you need to clean the DB
DatabaseCleaner.clean

# 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

I know this is an old question, but I thought this might be helpful to someone. This is a very fast way of cleaning out all data from a database.

tables = []
ActiveRecord::Base.connection.execute("show tables").each { |r| tables << r[0] }
tables = tables - ["schema_migrations"]
tables.each do |table|
  ActiveRecord::Base.connection.execute("DELETE FROM #{table} WHERE 1 = 1")
end

I use this technique in certain specs in an after(:all) block. This is much faster and more efficient than any of the Rails rake tasks for purging, migrating, reseting the database.

BTW: I'm pretty sure this would likely fail if you were enforcing foreign key constraints on the database side.


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.


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


Building up on @Vlad Zloteanu's answer, here is a version to remove all tables while keeping the user records and login sessions together with some meta information. Feel free to adjust the list of tables to your requirements.

# lib/tasks/db/truncate.rake

namespace :db do
  desc 'Truncate all tables except users state and meta'
  task truncate: :environment do
    conn = ActiveRecord::Base.connection
    tables = conn.tables - %w[
      sessions
      users
      roles
      users_roles
      schema_migrations
      ar_internal_metadata
    ]
    tables.each { |t| conn.execute("TRUNCATE #{t}") }

    puts "Truncated tables\n================\n#{tables.sort.join("\n")}"
  end
end

참고URL : https://stackoverflow.com/questions/1196172/how-to-delete-all-data-from-all-tables-in-rails

반응형