Rails DB Migration - ¿Cómo Eliminar una Tabla?


Agregué una tabla que pensé que iba a necesitar, pero ahora ya no planeo usarla. ¿Cómo debo quitar esa mesa?

Ya he ejecutado migraciones, por lo que la tabla está en mi base de datos. Me imagino que rails generate migration debería ser capaz de manejar esto, pero aún no he averiguado cómo.

He probado:
rails generate migration drop_tablename,
pero eso solo generó una migración vacía.

¿Cuál es la forma "oficial" de soltar una tabla en Rails?

Author: Nick Blaisdell, 2010-10-26

19 answers

No siempre podrá simplemente generar la migración para tener ya el código que desea. Puede crear una migración vacía y luego rellenarla con el código que necesita.

Puede encontrar información sobre cómo realizar diferentes tareas en una migración aquí:

Http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

Más específicamente, puede ver cómo eliminar una tabla utilizando el siguiente enfoque:

drop_table :table_name
 574
Author: Pete,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-05 17:23:05

Primero genere una migración vacía con el nombre que desee. Es importante hacerlo de esta manera ya que crea la fecha apropiada.

rails generate migration DropProductsTable

Esto generará un .archivo rb en / db / migrate / como 20111015185025_drop_products_table.rb

Ahora edita ese archivo para que se vea así:

class DropProductsTable < ActiveRecord::Migration
  def up
    drop_table :products
  end

  def down
    raise ActiveRecord::IrreversibleMigration
  end
end

Lo único que agregué fue drop_table :products y raise ActiveRecord::IrreversibleMigration.

Luego ejecuta rake db:migrate y te dejará caer la tabla.

 324
Author: Brandon O'Rourke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-08-10 01:29:03

Escriba su migración manualmente. Por ejemplo, ejecutar rails g migration DropUsers.

En cuanto al código de la migración, solo voy a citar el post de Maxwell Holder Rails Migration Checklist

MAL funcionamiento rake db:migrate y luego rake db:rollback fallará

class DropUsers < ActiveRecord::Migration
  def change
    drop_table :users
  end
end

BUENO-revela la intención de que la migración no debe ser reversible

class DropUsers < ActiveRecord::Migration
  def up
    drop_table :users
  end

  def down
    fail ActiveRecord::IrreversibleMigration
  end
end

MEJOR-es realmente reversible

class DropUsers < ActiveRecord::Migration
  def change
    drop_table :users do |t|
      t.string :email, null: false
      t.timestamps null: false
    end
  end
end
 264
Author: Beder Acosta Borges,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-27 15:25:02

Si bien las respuestas proporcionadas aquí funcionan correctamente, quería algo un poco más 'directo', lo encontré aquí: link Primero entra en la consola de rails:

$rails console

Entonces simplemente escriba:

ActiveRecord::Migration.drop_table(:table_name)

Y hecho, trabajó para mí!

 170
Author: lllllll,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-24 10:08:11

Es necesario crear un nuevo archivo de migración utilizando el siguiente comando

rails generate migration drop_table_xyz

Y escriba el código drop_table en el archivo de migración recién generado (db / migration / xxxxxxx_drop_table_xyz) como

drop_table :tablename

O si desea eliminar la tabla sin migración, simplemente abra la consola de rails mediante

$ rails c

Y ejecutar el siguiente comando

ActiveRecord::Base.connection.execute("drop table table_name")

O puede usar un comando más simplificado

ActiveRecord::Migration.drop_table(:table_name)
 34
Author: Shahzad Tariq,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-29 13:15:07
  1. rails g migración drop_users
  2. editar la migración
    class DropUsers < ActiveRecord::Migration
      def change
        drop_table :users do |t|
          t.string :name
          t.timestamps
        end
      end
    end
  1. rake db: migrar
 21
Author: Aashish Saini,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-31 14:48:28

Creo que, para ser completamente "oficial", tendría que crear una nueva migración, y poner drop_table en self.hasta. Auto.el método down debe contener todo el código para recrear la tabla en su totalidad. Presumiblemente ese código podría ser tomado de schema.rb en el momento de crear la migración.

Parece un poco extraño, poner código para crear una tabla que sabes que ya no vas a necesitar, pero eso mantendría todo el código de migración completo y "oficial", ¿verdad?

I solo hice esto para una mesa que necesitaba dejar caer, pero honestamente no probé el "abajo" y no estoy seguro de por qué lo haría.

 13
Author: Francis Potter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-04-03 22:50:40

Simplemente puede soltar una tabla desde la consola de rails. primero abra la consola

$ rails c

Luego pegue este comando en la consola

ActiveRecord::Migration.drop_table(:table_name)

Reemplace nombre_tabla por la tabla que desea eliminar.

También puede soltar la tabla directamente desde el terminal. simplemente ingrese en el directorio raíz de su aplicación y ejecute este comando

$ rails runner "Util::Table.clobber 'table_name'"
 10
Author: Farzpal Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-16 06:59:32

Abre la consola de rails

ActiveRecord::Base.connection.execute("drop table table_name")
 7
Author: manish nautiyal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-28 10:16:30

Puede revertir una migración de la manera en que está en la guía:

Http://guides.rubyonrails.org/active_record_migrations.html#reverting-previous-migrations

Generar una migración:

rails generate migration revert_create_tablename

Escribe la migración:

require_relative '20121212123456_create_tablename'

class RevertCreateTablename < ActiveRecord::Migration[5.0]
  def change
    revert CreateTablename    
  end
end

De esta manera también puede revertir y puede usar para revertir cualquier migración

 7
Author: Matheus Silva,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-05 17:42:34

La manera simple y oficial sería esta:

  rails g migration drop_tablename

Ahora vaya a su db/migrate y busque su archivo que contiene el drop_tablename como el nombre de archivo y edítelo a esto.

    def change
      drop_table :table_name
    end

Entonces necesitas ejecutar

    rake db:migrate 

En tu consola.

 6
Author: Mahesh Mesta,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-28 06:57:26

ActiveRecord::Base.connection.drop_table :table_name

 4
Author: nhegroj,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-10 19:54:43

Alternativa a elevar la excepción o intentar recrear una tabla ahora vacía - mientras se habilita la migración reversión, rehacer, etc. -

def change drop_table(:users, force: true) if ActiveRecord::Base.connection.tables.include?('users') end

 3
Author: aqwan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-20 16:15:28

Necesitaba eliminar nuestros scripts de migración junto con las propias tablas ...

class Util::Table < ActiveRecord::Migration

 def self.clobber(table_name)   
    # drop the table
    if ActiveRecord::Base.connection.table_exists? table_name
      puts "\n== " + table_name.upcase.cyan + " ! " 
           << Time.now.strftime("%H:%M:%S").yellow
      drop_table table_name 
    end

    # locate any existing migrations for a table and delete them
    base_folder = File.join(Rails.root.to_s, 'db', 'migrate')
    Dir[File.join(base_folder, '**', '*.rb')].each do |file|
      if file =~ /create_#{table_name}.rb/
        puts "== deleting migration: " + file.cyan + " ! "
             << Time.now.strftime("%H:%M:%S").yellow
        FileUtils.rm_rf(file)
        break
      end
    end
  end

  def self.clobber_all
    # delete every table in the db, along with every corresponding migration 
    ActiveRecord::Base.connection.tables.each {|t| clobber t}
  end

end

Desde la ventana de terminal ejecutar:

$ rails runner "Util::Table.clobber 'your_table_name'"

O

$ rails runner "Util::Table.clobber_all"
 2
Author: Aaron Henderson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-08 07:44:02

Ejecute este comando:-

rails g migration drop_table_name

Entonces:

rake db:migrate

O si está utilizando la base de datos MySQL entonces:

  1. iniciar sesión con la base de datos
  2. show databases;
  3. show tables;
  4. drop table_name;
 2
Author: Nitin Rakesh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-24 11:28:11

La mejor manera que puedes hacer es

rails g migration Drop_table_Users

Luego haga lo siguiente

rake db:migrate
 1
Author: Anoob K Bava,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-14 12:52:03

Ejecutar

rake db:migrate:down VERSION=<version>

Donde <version> es el número de versión del archivo de migración que desea revertir.

Ejemplo: -

rake db:migrate:down VERSION=3846656238
 1
Author: Rankit Ranjan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-08 07:16:19

Si desea eliminar una tabla específica, puede hacer

$ rails db:migrate:up VERSION=[Here you can insert timestamp of table]

De lo contrario, si desea eliminar toda su base de datos, puede hacer

$rails db:drop
 0
Author: Nicollas Matheus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-02 22:17:17

Drop Table / Migration

Ejecutar:- rails rails generar migración DropTablename

Exp: - rails rails generate migration DropProducts

 -1
Author: Pankaj Dhote,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-20 14:54:46