Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reset a single table in rails?

I want the primary key values to start from 1 again.

like image 287
Yury Kaspiarovich Avatar asked Dec 17 '09 11:12

Yury Kaspiarovich


People also ask

How to reset id in rails?

Resetting primary key sequence in Rails can be achieved by simply calling method reset_pk_sequence! on ActiveRecord with table_name .


2 Answers

A lot of people (like me) come here to find how to delete all the data in the table. Here you go:

$ rails console  > ModelName.delete_all 

or

> ModelName.destroy_all 

destroy_all checks dependencies and callbacks, and takes a little longer. delete_all is a straight SQL query.

More info here: http://apidock.com/rails/ActiveRecord/Base/delete_all/class

like image 83
Flaviu Avatar answered Sep 18 '22 20:09

Flaviu


I've been using the following from rails console to delete everything in the table and then reset the index counter (Ruby 2 & Rails 4):

> ModelName.delete_all > ActiveRecord::Base.connection.reset_pk_sequence!('plural_model_name') 
like image 44
Meltemi Avatar answered Sep 19 '22 20:09

Meltemi