Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Model.delete_all and make the ids start back at 1?

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!

like image 497
Andrew Avatar asked Feb 28 '13 20:02

Andrew


People also ask

How do you undo a command in rails?

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

How do you use destroy in Ruby on rails?

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.

What is the difference between delete and destroy in rails?

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.

What is soft delete in rails?

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.


2 Answers

if you use postgresql you can execute this code

ActiveRecord::Base.connection.reset_pk_sequence!(Model.table_name)

after Model.destroy_all

like image 99
buncis Avatar answered Oct 08 '22 14:10

buncis


The best and easy way :

ActiveRecord::Base.connection.reset_pk_sequence!('table_name')

Ps : don't forget the 's' after the table_name

like image 36
Gregdebrick Avatar answered Oct 08 '22 14:10

Gregdebrick