Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate table(s) with rails console

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?

like image 577
CaptainCarl Avatar asked Nov 01 '12 08:11

CaptainCarl


People also ask

How do I truncate data in a table?

The SQL TRUNCATE TABLE command is used to delete complete data from an existing table. You can also use DROP TABLE command to delete complete table but it would remove complete table structure form the database and you would need to re-create this table once again if you wish you store some data.

How delete all data from table in rails?

During development, you might find yourself needing to delete everything from a specific database table to refresh your data. You could drop the whole database and bring it back up again with rake:db:drop, rake:db:setup , but that's slow and indiscriminate.

How do I truncate a table in Toad?

To truncate a table, the table must be in your schema or you must have the DROP ANY TABLE system privilege. To specify the CASCADE clause, all affected child tables must be in your schema or you must have the DROP ANY TABLE system privilege. Specify the schema and name of the table to be truncated.


1 Answers

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") 

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}'") 
like image 53
Ravi Sankar Raju Avatar answered Sep 27 '22 22:09

Ravi Sankar Raju