开发者

How to reset a single table in rails?

开发者 https://www.devze.com 2022-12-14 02:06 出处:网络
I want the primary key 开发者_JAVA百科values to start from 1 again.A lot of people (like me) come here to find how to delete all the data in the table. Here you go:

I want the primary key 开发者_JAVA百科values to start from 1 again.


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


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


To reset the index/primary key in SQLite just type:

$ rails console
> ActiveRecord::Base.connection.execute("DELETE from sqlite_sequence where name = 'yourtablename'")


Since Rails 4.2 you can use truncate directly on an ActiveRecord connection:

ActiveRecord::Base.connection.truncate(:table_name)

This wipes all data and resets the autoincrement counters in the table. Works in MySQL and Postgres, does not work in Sqlite.


@khelll's link is helpful. The command you want to truncate one table is:

ActiveRecord::Base.connection.execute("TRUNCATE #{table_name}")


Add gem 'database_cleaner' to your Gemfile, run $ bundle install, and then:

> DatabaseCleaner.clean_with(:truncation, :only => ['yourtablename'])

You can specify more tables:

> DatabaseCleaner.clean_with(:truncation, :only => ['table1', 'table2', 'table3'])

If you leave the last parameter out, it will truncate the whole database:

> DatabaseCleaner.clean_with(:truncation) # your database is truncated


I'm using Rails 4.2.0 and Sqlite3

Here's what worked for me (taking a bit from all of the above):

$ rails c
> ModelName.delete_all
> ActiveRecord::Base.connection.execute("DELETE from sqlite_sequence where name = 'table_name'")

I was then able to add new records to my table with the index starting back at 1


For anyone else looking for the answer to this question when the database is Postgres, you can do this from the Rails console:

rails console
irb(main):028:0> ActiveRecord::Base.connection.execute("SELECT SETVAL('accounts_id_seq', 1)")

Where the accounts in the accounts_id_seq is the name of the table.

0

精彩评论

暂无评论...
验证码 换一张
取 消