使用 rails 控制台截断表 [英] Truncate table(s) with rails console

查看:66
本文介绍了使用 rails 控制台截断表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个测试数据库,现在里面塞满了垃圾.现在我已经在 rails 控制台中完成了一些 Table.destroy_all 命令,它删除了所有记录和依赖项,这很棒.然而;我想截断所有内容,以便 ID 等再次从 1 开始.Rails 3 有什么办法吗?

I have this testingdatabase which, by now, is stuffed with junk. Now I've done a few Table.destroy_all commands in the rails console which deletes all records and dependencies which is awesome. However; I'd like to truncate everything so the ID's etc. start at 1 again. Is there any way in Rails 3?

推荐答案

接受的答案仅在您需要重新创建整个数据库时才有效.
删除单个表(带有回调)并使 ID 从 1 开始:

The accepted answer only works if you need to recreate the whole database.
To drop a single table (with the callbacks) and to get the IDs to start from 1:

Model.destroy_all # Only necessary if you want to trigger callbacks.
ActiveRecord::Base.connection.execute("TRUNCATE #{table_name} RESTART IDENTITY")

如果您使用的是 Sqlite,它不支持截断,请执行以下操作:

If you are using Sqlite, it does not support truncate so do the following:

Model.destroy_all # Only necessary if you want to trigger callbacks.
ActiveRecord::Base.connection.execute("Delete from #{table_name}")
ActiveRecord::Base.connection.execute("DELETE FROM SQLITE_SEQUENCE WHERE name='#{table_name}'")

这篇关于使用 rails 控制台截断表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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