本文介绍了删除一切从所有表(在ActiveRecord的)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以做 Post.delete_all
全部删除我的帖子,但如果我要删除所有帖子,评论,博客等即,我怎么遍历在我所有的模型和运行 DELETE_ALL
的方法?
解决方案
耙分贝:重设
据重现从迁移你的表。
由于建议的意见,更快的方式做到这一点(但你要添加一个新的rake任务)是:
命名空间:DB做
DESC截断所有表
任务:截断=> :环境做
康恩=的ActiveRecord :: Base.connection来
表= conn.execute(节目表)地图{|:R | R [O]}
tables.deleteschema_migrations
tables.each {| T | conn.execute(TRUNCATE#【T】)}
结束
结束
响应复制的:回答SO
I can do Post.delete_all
to delete all my posts, but what if I want to delete all posts, comments, blogs, etc. I.e., how do I iterate over all my models and run the delete_all
method?
解决方案
rake db:reset
It recreates your table from migrations.
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
Response copied from: answer on SO.
这篇关于删除一切从所有表(在ActiveRecord的)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!