且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何从Rails的所有表中删除所有数据?

更新时间:2023-02-10 14:36:06

rake db:reset 

它通过迁移来重新创建表。

It recreates your table from migrations.

如注释中所建议,这是一种更快的方法(但您必须添加一个新的rake任务)是:

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

从以下地址复制的响应:对SO的回答

Response copied from: answer on SO.