如何从Rails中的所有表中删除所有数据? [英] How to delete all data from all tables in Rails?
本文介绍了如何从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 上的回答.
这篇关于如何从Rails中的所有表中删除所有数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文