I'm using Model.delete_all in the Rails console to delete a table, but I noticed that the id numbers don't reset, they just start where it left off. How do I delete a table and make the ids start back at 1?
It's actually not a big deal, I'm just curious and think it'd be cleaner this way. Thank you!
To undo a rails generate command, run a rails destroy command. You can then edit the file and run rake db:migrate again. (See how to roll back a Migration file to rollback a specific migration or multiple migrations.)
To create the controller action for the destroy-resource, we perform three substeps: (1) create an empty destroy-resource controller action, (2) add code to the action that retrieves the model object, and (3) add code to the action that destroys the model object and responds to the browser with an HTTP redirect.
Rails Delete operation using delete method Unlike the destroy method, with delete, you can remove a record directly from the database. Any dependencies to other records in the model are not taken into account. The method delete only deletes that one row in the database and nothing else.
Deleting something from your database is very common and handled very easily by rails as part of a CRUD action. In some cases, it is useful to create a “soft delete”, meaning that the deleted element will still exist in the database but won't appear to the user.
if you use postgresql you can execute this code
ActiveRecord::Base.connection.reset_pk_sequence!(Model.table_name)
after Model.destroy_all
The best and easy way :
ActiveRecord::Base.connection.reset_pk_sequence!('table_name')
Ps : don't forget the 's' after the table_name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With