Truncate table(s) with rails console

前端 未结 9 1365
北恋
北恋 2021-02-02 05:51

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

9条回答
  •  时光取名叫无心
    2021-02-02 06:20

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

提交回复
热议问题