ahuang7
ahuang7

Reputation: 2190

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!

Upvotes: 14

Views: 10289

Answers (7)

buncis
buncis

Reputation: 2502

if you use postgresql you can execute this code

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

after Model.destroy_all

Upvotes: 8

Gregdebrick
Gregdebrick

Reputation: 571

The best and easy way :

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

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

Upvotes: 6

lafeber
lafeber

Reputation: 2780

If you only need to reset the ids:

ActiveRecord::Base.connection.execute('ALTER TABLE table_name AUTO_INCREMENT = 1')

Upvotes: 4

Sakeer
Sakeer

Reputation: 2006

To drop just one table (with the callbacks) and to get the IDs start from 1, there is no straight forward way in rails to do it.

You can do

1) Model.destroy_all

2) ActiveRecord::Base.connection.execute("TRUNCATE table_name")

which will handle all that you want, for a single table, if that's what you need

Upvotes: 11

AdamT
AdamT

Reputation: 6485

one liner

rake db:drop && rake db:create && rake db:migrate

back in business

Upvotes: 0

moonfly
moonfly

Reputation: 1820

It depends on the DB. In your app you shouldn't rely on the fact that IDs start with 1 and go sequentially, or even always increase for new records. If you want a fresh DB, you can always do rake db:drop, then rake db:create.

Upvotes: 1

hwatkins
hwatkins

Reputation: 1416

Most databases have a concept of a sequence which auto increments as it's used. ActiveRecord uses the underlying database sequence to create primary keys. This gem (https://github.com/splendeo/activerecord-reset-pk-sequence) may help reset it for you depending on your database.

Upvotes: 7

Related Questions