Reputation: 1954
I'm using PostgreSQL database on Rails 2.3.8 and I need to restart auto increment ID on my table. How can I do that?
Upvotes: 10
Views: 10892
Reputation: 3085
You can use ActiveRecord in Rails.
You can easily do it from your rails console by running the following command:
Table_name.reset_primary_key
You can also use SQL
:
TRUNCATE TABLE foo RESTART IDENTITY;
Upvotes: 1
Reputation: 758
Try:
ActiveRecord::Base.connection.reset_pk_sequence!(table_name)
and check this answer for more details: https://stackoverflow.com/a/7814519/1392282
Upvotes: 5
Reputation: 344
If you want to delete all data from table and want to reset id as well then try below code.
ActiveRecord::Base.connection.execute("TRUNCATE TABLE your_table_name RESTART IDENTITY")
But if some relationship is present with table and you want to delete all data from table as well as related table data then try below code.
ActiveRecord::Base.connection.execute("TRUNCATE TABLE your_table_name RESTART IDENTITY CASCADE")
Thanks and please suggest if correction needed.
Upvotes: 3
Reputation: 3587
You could do it in the following way:
ActiveRecord::Base.connection.execute("TRUNCATE TABLE your_table_name RESTART IDENTITY")
Upvotes: 11
Reputation: 6548
If you truncate the table you can use the RESTART IDENTITY clause on the end.
Example:
TRUNCATE TABLE foo RESTART IDENTITY;
Upvotes: 14
Reputation: 2084
You can do it directly in PostgreSQL using "alter sequence": http://www.postgresql.org/docs/current/static/sql-altersequence.html
Particularly "restart with"
I don't know how you would do it via the rails abstraction.
Upvotes: 5