Как сбросить одну таблицу в рельсах? - PullRequest
83 голосов
/ 17 декабря 2009

Я хочу, чтобы значения первичного ключа снова начинались с 1.

Ответы [ 9 ]

177 голосов
/ 17 сентября 2011

Многие люди (как и я) приходят сюда, чтобы найти, как удалить все данные в таблице. Вот, пожалуйста:

$ rails console

> ModelName.delete_all

или

> ModelName.destroy_all

destroy_all проверяет зависимости и обратные вызовы и занимает немного больше времени. delete_all - прямой запрос SQL.

Подробнее здесь: http://apidock.com/rails/ActiveRecord/Base/delete_all/class

41 голосов
/ 11 октября 2013

Я использовал следующее из консоли rails, чтобы удалить все в таблице и затем сбросить счетчик индекса (Ruby 2 & Rails 4):

> ModelName.delete_all
> ActiveRecord::Base.connection.reset_pk_sequence!('plural_model_name')
26 голосов
/ 05 июля 2012

Чтобы сбросить индекс / первичный ключ в SQLite, просто наберите:

$ rails console
> ActiveRecord::Base.connection.execute("DELETE from sqlite_sequence where name = 'yourtablename'")
17 голосов
/ 15 мая 2012

@ khelll ссылка полезна. Команда, которую вы хотите усечь одну таблицу:

ActiveRecord::Base.connection.execute("TRUNCATE #{table_name}")
10 голосов
/ 03 октября 2012

Добавьте gem 'database_cleaner' в ваш Gemfile, запустите $ bundle install, а затем:

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

Вы можете указать больше таблиц:

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

Если вы пропустите последний параметр, он усекает всю базу данных:

> DatabaseCleaner.clean_with(:truncation) # your database is truncated
9 голосов
/ 21 мая 2017

Начиная с Rails 4.2, вы можете использовать truncate непосредственно на ActiveRecord соединении :

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

стирает все данные , а сбрасывает счетчики автоинкремента в таблице. Работает в MySQL и Postgres, не работает в Sqlite.

6 голосов
/ 22 мая 2015

Я использую Rails 4.2.0 и Sqlite3

Вот что сработало для меня (немного из всего вышесказанного):

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

Затем я смог добавить новые записи в мою таблицу с индексом, начинающимся с 1

3 голосов
/ 17 декабря 2009

Я не думаю, что вы можете сделать это. Однако вы могли бы написать собственное задание на рейк

Для вашей информации, вы можете получить список доступных для рейка заданий:

rake --tasks

Вы получите что-то вроде:

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

1012 * через *

1 голос
/ 28 сентября 2013

Для тех, кто ищет ответ на этот вопрос, когда база данных Postgres, вы можете сделать это из консоли Rails:

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

Где accounts в accounts_id_seq является именем таблицы.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...