如何在rails中重置单个表?

时间:2021-05-02 23:25:04

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

我想让主键值从1开始。

10 个解决方案

#1


23  

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

要重置SQLite中的索引/主键,只需输入:

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

#2


166  

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.

驱逐舰_all检查依赖项和回调,并需要更长的时间。delete_all是一个直接的SQL查询。

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

更多信息:http://apidock.com/rails/ActiveRecord/Base/delete_all/class

#3


37  

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

我一直在使用rails控制台的以下命令删除表中的所有内容,然后重置索引计数器(Ruby 2 & rails 4):

> ModelName.delete_all
> ActiveRecord::Base.connection.reset_pk_sequence!('plural_model_name')

#4


17  

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

@khelll的链接是有帮助的。您想截断一个表的命令是:

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

#5


10  

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

将gem 'database_cleaner'添加到Gemfile中,运行$ bundle安装,然后:

> 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

#6


6  

I'm using Rails 4.2.0 and Sqlite3

我使用的是Rails 4.2.0和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

然后我可以在表中添加新的记录,索引从1开始

#7


5  

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

既然Rails 4.2可以在ActiveRecord连接上直接使用truncatetable:

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.

这将删除所有数据并重置表中的自动增量计数器。在MySQL和Postgres中工作,在Sqlite中不工作。

#8


3  

I don't think that you can do that. However you could write your own rake task

我认为你做不到。但是,您可以编写自己的rake任务

For your information, you can get the list of rake tasks available by doing:

关于您的信息,您可以通过以下操作获得rake任务列表:

rake --tasks

You'll get something like:

你会得到一个类似于:

rake backups:clear             # Cleanup Backup files
rake clear                     # Cleanup temporary, log and backup files
rake db:fixtures:load          # Load fixtures into the current environment's database.  Load specific fixtures using FIXTURES=x,y
rake db:migrate                # Migrate the database through scripts in db/migrate. Target specific version with VERSION=x
rake db:schema:dump            # Create a db/schema.rb file that can be portably used against any DB supported by AR
rake db:schema:load            # Load a schema.rb file into the database
rake db:sessions:clear         # Clear the sessions table
rake db:sessions:create        # Creates a sessions table for use with CGI::Session::ActiveRecordStore
rake db:structure:dump         # Dump the database structure to a SQL file
rake db:test:clone             # Recreate the test database from the current environment's database schema
rake db:test:clone_structure   # Recreate the test databases from the development structure
rake db:test:prepare           # Prepare the test database and load the schema
rake db:test:purge             # Empty the test database
rake doc:app                   # Build the app HTML Files
rake doc:clobber_app           # Remove rdoc products
rake doc:clobber_plugins       # Remove plugin documentation
rake doc:clobber_rails         # Remove rdoc products
rake doc:plugins               # Generate documation for all installed plugins
rake doc:rails                 # Build the rails HTML Files
rake doc:reapp                 # Force a rebuild of the RDOC files
rake doc:rerails               # Force a rebuild of the RDOC files
rake log:clear                 # Truncates all *.log files in log/ to zero bytes
rake rails:freeze:edge         # Lock to latest Edge Rails or a specific revision with REVISION=X (ex: REVISION=4021) or a tag with TAG=Y (ex: TAG=rel_1-1-0)
rake rails:freeze:gems         # Lock this application to the current gems (by unpacking them into vendor/rails)
rake rails:unfreeze            # Unlock this application from freeze of gems or edge and return to a fluid use of system gems
rake rails:update              # Update both configs, scripts and public/javascripts from Rails
rake rails:update:configs      # Update config/boot.rb from your current rails install
rake rails:update:javascripts  # Update your javascripts from your current rails install
rake rails:update:scripts      # Add new scripts to the application script/ directory
rake stats                     # Report code statistics (KLOCs, etc) from the application
rake test                      # Test all units and functionals
rake test:functionals          # Run the functional tests in test/functional
rake test:integration          # Run the integration tests in test/integration
rake test:plugins              # Run the plugin tests in vendor/plugins/**/test (or specify with PLUGIN=name)
rake test:recent               # Test recent changes
rake test:uncommitted          # Test changes since last checkin (only Subversion)
rake test:units                # Run the unit tests in test/unit
rake tmp:assets:clear          # Clears all files in tmp/test/assets
rake tmp:cache:clear           # Clears all files and directories in tmp/cache
rake tmp:clear                 # Clear session, cache, and socket files from tmp/
rake tmp:create                # Creates tmp directories for sessions, cache, and sockets
rake tmp:pids:clear            # Clears all files in tmp/pids
rake tmp:sessions:clear        # Clears all files in tmp/sessions
rake tmp:sockets:clear         # Clears all files in tmp/sockets

via

通过

#9


2  

Have a look here, you still might need a little customization to truncate a specific table.

看看这里,您仍然可能需要一些定制来截断特定的表。

#10


1  

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

对于任何想在数据库是Postgres时查找这个问题的答案的人来说,您可以从Rails控制台执行以下操作:

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.

其中accounts_id_seq中的帐户是表的名称。

#1


23  

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

要重置SQLite中的索引/主键,只需输入:

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

#2


166  

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.

驱逐舰_all检查依赖项和回调,并需要更长的时间。delete_all是一个直接的SQL查询。

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

更多信息:http://apidock.com/rails/ActiveRecord/Base/delete_all/class

#3


37  

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

我一直在使用rails控制台的以下命令删除表中的所有内容,然后重置索引计数器(Ruby 2 & rails 4):

> ModelName.delete_all
> ActiveRecord::Base.connection.reset_pk_sequence!('plural_model_name')

#4


17  

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

@khelll的链接是有帮助的。您想截断一个表的命令是:

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

#5


10  

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

将gem 'database_cleaner'添加到Gemfile中,运行$ bundle安装,然后:

> 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

#6


6  

I'm using Rails 4.2.0 and Sqlite3

我使用的是Rails 4.2.0和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

然后我可以在表中添加新的记录,索引从1开始

#7


5  

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

既然Rails 4.2可以在ActiveRecord连接上直接使用truncatetable:

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.

这将删除所有数据并重置表中的自动增量计数器。在MySQL和Postgres中工作,在Sqlite中不工作。

#8


3  

I don't think that you can do that. However you could write your own rake task

我认为你做不到。但是,您可以编写自己的rake任务

For your information, you can get the list of rake tasks available by doing:

关于您的信息,您可以通过以下操作获得rake任务列表:

rake --tasks

You'll get something like:

你会得到一个类似于:

rake backups:clear             # Cleanup Backup files
rake clear                     # Cleanup temporary, log and backup files
rake db:fixtures:load          # Load fixtures into the current environment's database.  Load specific fixtures using FIXTURES=x,y
rake db:migrate                # Migrate the database through scripts in db/migrate. Target specific version with VERSION=x
rake db:schema:dump            # Create a db/schema.rb file that can be portably used against any DB supported by AR
rake db:schema:load            # Load a schema.rb file into the database
rake db:sessions:clear         # Clear the sessions table
rake db:sessions:create        # Creates a sessions table for use with CGI::Session::ActiveRecordStore
rake db:structure:dump         # Dump the database structure to a SQL file
rake db:test:clone             # Recreate the test database from the current environment's database schema
rake db:test:clone_structure   # Recreate the test databases from the development structure
rake db:test:prepare           # Prepare the test database and load the schema
rake db:test:purge             # Empty the test database
rake doc:app                   # Build the app HTML Files
rake doc:clobber_app           # Remove rdoc products
rake doc:clobber_plugins       # Remove plugin documentation
rake doc:clobber_rails         # Remove rdoc products
rake doc:plugins               # Generate documation for all installed plugins
rake doc:rails                 # Build the rails HTML Files
rake doc:reapp                 # Force a rebuild of the RDOC files
rake doc:rerails               # Force a rebuild of the RDOC files
rake log:clear                 # Truncates all *.log files in log/ to zero bytes
rake rails:freeze:edge         # Lock to latest Edge Rails or a specific revision with REVISION=X (ex: REVISION=4021) or a tag with TAG=Y (ex: TAG=rel_1-1-0)
rake rails:freeze:gems         # Lock this application to the current gems (by unpacking them into vendor/rails)
rake rails:unfreeze            # Unlock this application from freeze of gems or edge and return to a fluid use of system gems
rake rails:update              # Update both configs, scripts and public/javascripts from Rails
rake rails:update:configs      # Update config/boot.rb from your current rails install
rake rails:update:javascripts  # Update your javascripts from your current rails install
rake rails:update:scripts      # Add new scripts to the application script/ directory
rake stats                     # Report code statistics (KLOCs, etc) from the application
rake test                      # Test all units and functionals
rake test:functionals          # Run the functional tests in test/functional
rake test:integration          # Run the integration tests in test/integration
rake test:plugins              # Run the plugin tests in vendor/plugins/**/test (or specify with PLUGIN=name)
rake test:recent               # Test recent changes
rake test:uncommitted          # Test changes since last checkin (only Subversion)
rake test:units                # Run the unit tests in test/unit
rake tmp:assets:clear          # Clears all files in tmp/test/assets
rake tmp:cache:clear           # Clears all files and directories in tmp/cache
rake tmp:clear                 # Clear session, cache, and socket files from tmp/
rake tmp:create                # Creates tmp directories for sessions, cache, and sockets
rake tmp:pids:clear            # Clears all files in tmp/pids
rake tmp:sessions:clear        # Clears all files in tmp/sessions
rake tmp:sockets:clear         # Clears all files in tmp/sockets

via

通过

#9


2  

Have a look here, you still might need a little customization to truncate a specific table.

看看这里,您仍然可能需要一些定制来截断特定的表。

#10


1  

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

对于任何想在数据库是Postgres时查找这个问题的答案的人来说,您可以从Rails控制台执行以下操作:

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.

其中accounts_id_seq中的帐户是表的名称。