13

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!

Andrew
  • 1,167
  • 1
  • 10
  • 16
  • 1
    similar question with answer here: http://stackoverflow.com/questions/2097052/rails-way-to-reset-seed-on-id-field – karl li Feb 14 '17 at 05:43

7 Answers7

11

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

Sakeer
  • 1,885
  • 3
  • 24
  • 43
8

if you use postgresql you can execute this code

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

after Model.destroy_all

buncis
  • 2,148
  • 1
  • 23
  • 25
7

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.

hwatkins
  • 1,416
  • 8
  • 11
6

The best and easy way :

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

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

Gregdebrick
  • 533
  • 6
  • 14
3

If you only need to reset the ids:

ActiveRecord::Base.connection.execute('ALTER TABLE table_name AUTO_INCREMENT = 1')
lafeber
  • 2,683
  • 1
  • 27
  • 29
1

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.

moonfly
  • 1,810
  • 11
  • 14
0

one liner

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

back in business

AdamT
  • 6,405
  • 10
  • 49
  • 75
  • didn't work for me I got an error running even the first part of that https://pastebin.com/raw/S3AgciCn – barlop Dec 23 '17 at 05:45
  • @barlop this answer is from a few years ago. perhaps the other answers can help you. also, make sure your server isn't running. – AdamT Dec 23 '17 at 12:07