2009-12-17 15 views

Respuesta

23

Para restablecer la clave del índice/primaria en SQLite sólo tiene que escribir:

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

inspirándose en su respuesta ... 'Person.connection.execute ('delete from people')' 'Person.connection.execute (" update sqlite_sequence set seq = 0 donde name = 'Gente' ")' – mamesaye

+1

En caso de que alguien haya intentado esto y haya recibido un error, hice 'ActiveRecord :: Base.connection.execute (" DELETE from 'yourtablename' ")' y funcionó porque me daría un error que dijo 'sqlite_sequence donde name = 'yourtablename' no es un nombre de tabla válido' o algo así. – l1zZY

3

No creo que puedas hacer eso. Sin embargo, puede write your own rake task

Para su información, se puede obtener la lista de tareas del rastrillo disponibles haciendo:

rake --tasks 

Usted obtendrá algo como:

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

+5

Esto fue seleccionado como la mejor respuesta, pero en realidad no responde la pregunta. @OP, ¿cómo lo hiciste? – CharlieMezak

2

Eche un vistazo here, aún podría necesitar una pequeña personalización para truncar una tabla específica.

166

Muchas personas (como yo) vienen aquí para encontrar cómo eliminar todos los datos en la tabla. Aquí van:

$ rails console 

> ModelName.delete_all 

o

> ModelName.destroy_all 

destroy_all comprueba dependencias y devoluciones de llamada, y tarda un poco más. delete_all es una consulta SQL directa.

Más información aquí: http://apidock.com/rails/ActiveRecord/Base/delete_all/class

+8

Esta solución restablece las entradas de la tabla, pero no la clave principal. –

+4

Sí, esto es genial, pero quiero restablecer el índice. Ni delete_all ni destroy_all restablecen el índice a 1. –

+2

Esta no es la respuesta a la pregunta. ¿Por qué esto recibió tantos votos? >< –

17

@ enlace de khelll es útil. El comando que desea truncar una tabla es:

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

Parece que no funciona en Rails 4 – Epigene

10

Añadir gem 'database_cleaner' a su Gemfile, ejecute $ bundle install, y luego:

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

puede especificar más tablas:

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

Si deja el último parámetro de salida, se truncará a toda la base de datos:

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

Perfecto, gracias. Esto es lo único que funcionó para mí en Sqlite. –

1

Para cualquier otra persona en busca de la respuesta a esta pregunta cuando la base de datos es PostgreSQL, puede hacerlo desde la consola de Rails:

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

Cuando el accounts en el accounts_id_seq es el nombre de la tabla.

35

He estado usando lo siguiente de los carriles de la consola para borrar todo en la mesa y luego reiniciar el contador de índice (Ruby 2 & Carriles 4):

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

solo funciona con postgreSQL – achabacha322

+3

Esto funcionó muy bien para mí, pero un pequeño detalle es que su 'model_name' en el comando de reinicio necesita plural, como el nombre real de la tabla NO el nombre singular del modelo. –

6

estoy usando Rails 4.2.0 y Sqlite3

Esto es lo que funcionó para mí (teniendo un poco de todo lo anterior):

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

Yo era entonces capaz de agregar nuevos registros a mi mesa con el índice a partir de vuelta en 1

3

Desde Rails 4.2 se puede utilizar truncate directamente en un ActiveRecord connection:

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

Esta borra todos los datos y restablece los contadores autoincrement en la tabla. Funciona en MySQL y Postgres, no funciona en en Sqlite.

Cuestiones relacionadas