如何从Rails的所有表中删除所有数据? [英] How to delete all data from all tables in Rails?

查看:154
本文介绍了如何从Rails的所有表中删除所有数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以执行 Post.delete_all 删除我的所有帖子,但是如果我想删除所有帖子,评论,博客等怎么办?

I can do Post.delete_all to delete all my posts, but what if I want to delete all posts, comments, blogs, etc.?

如何迭代所有模型并运行 delete_all 方法?

How do I iterate over all my models and run the delete_all method?

推荐答案

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.

这篇关于如何从Rails的所有表中删除所有数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆