且构网

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

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

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

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 上的回答.