Migracja rails DB-jak zrzucić tabelę?

Dodałem tabelę, którą myślałem, że będę potrzebował, ale teraz nie planuję jej używać. Jak usunąć ten stół?

Już uruchomiłem migracje, więc tabela jest w mojej bazie danych. Myślę, że rails generate migration powinien być w stanie poradzić sobie z tym, ale nie wiem jeszcze jak.

Próbowałem:
rails generate migration drop_tablename,
ale to spowodowało pustą migrację.

Jaki jest "oficjalny" sposób na upuszczenie tabeli w Rails?

Author: Nick Blaisdell, 2010-10-26

19 answers

Nie zawsze będziesz w stanie po prostu wygenerować migrację, aby mieć już kod, który chcesz. Możesz utworzyć pustą migrację, a następnie wypełnić ją potrzebnym kodem.

Możesz znaleźć informacje o tym, jak wykonać różne zadania w migracji tutaj:

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

Dokładniej, możesz zobaczyć, jak upuścić tabelę za pomocą następującego podejścia:

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/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-05 17:23:05

Najpierw Wygeneruj pustą migrację o dowolnej nazwie. Ważne jest, aby zrobić to w ten sposób, ponieważ tworzy odpowiednią datę.

rails generate migration DropProductsTable

To wygeneruje .plik rb w /db / migrate / like 20111015185025_drop_products_table.rb

Teraz edytuj ten plik, aby wyglądał tak:

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

  def down
    raise ActiveRecord::IrreversibleMigration
  end
end

Dodałem tylko drop_table :products i raise ActiveRecord::IrreversibleMigration.

Następnie uruchom rake db:migrate i spadnie stół dla Ciebie.

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2012-08-10 01:29:03

Napisz migrację ręcznie. Np. run rails g migration DropUsers.

Co do kodu migracji to zacytuję post Maxwella hold ' a Rails Migration Checklist

BAD-running rake db:migrate and then rake db:rollback will fail

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

GOOD-ujawnia intencję, że migracja nie powinna być odwracalna

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

  def down
    fail ActiveRecord::IrreversibleMigration
  end
end

Lepszy - jest właściwie odwracalny

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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-27 15:25:02

Chociaż odpowiedzi podane tutaj działają poprawnie, chciałem czegoś bardziej "prostego", znalazłem to tutaj: link Najpierw wejdź do konsoli rails:

$rails console

Następnie wpisz:

ActiveRecord::Migration.drop_table(:table_name)

I gotowe, zadziałało dla mnie!

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-24 10:08:11

Musisz utworzyć nowy plik migracji używając następującego polecenia

rails generate migration drop_table_xyz

I zapisz kod drop_table w nowo wygenerowanym pliku migracji (db/migration/xxxxxxx_drop_table_xyz) jak

drop_table :tablename

Lub jeśli chcesz upuścić tabelę bez migracji, po prostu otwórz konsolę rails przez

$ rails c

I wykonaj następujące polecenie

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

Lub możesz użyć bardziej uproszczonego polecenia

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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-29 13:15:07
  1. rails g migration drop_users
  2. edytuj migrację
    class DropUsers < ActiveRecord::Migration
      def change
        drop_table :users do |t|
          t.string :name
          t.timestamps
        end
      end
    end
  1. rake db: migrate
 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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-31 14:48:28

Myślę, że aby być całkowicie "oficjalnym", musisz utworzyć nową migrację i umieścić drop_table w sobie.w górę. Jaźń.metoda down powinna wtedy zawierać cały kod, aby odtworzyć tabelę w całości. Prawdopodobnie ten kod mógłby być zaczerpnięty ze schematu.rb w momencie tworzenia migracji.

Wydaje się trochę dziwne, aby umieścić w kodzie, aby utworzyć tabelę wiesz, że nie będą już potrzebne, ale to by utrzymać cały kod migracji kompletne i "oficjalne", prawda?

I po prostu zrobił to dla tabeli musiałem upuścić, ale szczerze nie testować "w dół" i nie wiem, dlaczego miałbym.

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-03 22:50:40

Możesz po prostu upuścić tabelę z konsoli rails. najpierw otwórz konsolę

$ rails c

Następnie wklej to polecenie w konsoli

ActiveRecord::Migration.drop_table(:table_name)

Zastąp table_name tabelą, którą chcesz usunąć.

Możesz również zrzucić tabelę bezpośrednio z terminala. wystarczy wejść do katalogu głównego aplikacji i uruchomić to polecenie

$ 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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-10-16 06:59:32

Otwórz konsolę 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/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-28 10:16:30

Możesz cofnąć migrację tak, jak jest w przewodniku:

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

Wygeneruj migrację:

rails generate migration revert_create_tablename

Napisz migrację:

require_relative '20121212123456_create_tablename'

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

W ten sposób można również wycofać i można użyć do odwrócenia dowolnej migracji

 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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-05 17:42:34

Prosty i oficjalny sposób byłby taki:

  rails g migration drop_tablename

Teraz przejdź do db / migrate i poszukaj pliku, który zawiera nazwę drop_tablename jako nazwę pliku i edytuj go do tego.

    def change
      drop_table :table_name
    end

Następnie musisz uruchomić

    rake db:migrate 
Na konsoli.
 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/doraprojects.net/template/agent.layouts/content.php on line 54
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/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-10 19:54:43

Alternatywa dla wywołania wyjątku lub próby odtworzenia pustej tabeli - jednocześnie umożliwiając migrację rollback, ponów itp.]}

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/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-20 16:15:28

Musiałem usunąć nasze Skrypty migracji wraz z samymi tabelami ...

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

Z okna terminala Uruchom:

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

Lub

$ 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/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-08 07:44:02

Uruchom to polecenie:-

rails g migration drop_table_name

Potem:

rake db:migrate

Lub jeśli używasz bazy danych MySql to:

  1. logowanie z bazy danych
  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/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-24 11:28:11

The best way you can do is

rails g migration Drop_table_Users

Następnie wykonaj następujące czynności

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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-14 12:52:03

Run

rake db:migrate:down VERSION=<version>

Gdzie <version> jest numerem wersji pliku migracji, który chcesz przywrócić.

Przykład:-

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/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-08 07:16:19

Jeśli chcesz upuścić konkretną tabelę możesz zrobić

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

W przeciwnym razie, jeśli chcesz upuścić całą bazę danych, możesz to zrobić

$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/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-02 22:17:17

Drop Table / Migration

Run:- $ rails generuje migrację DropTablename

Exp: - $ 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/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-20 14:54:46