Rails 数据库迁移 - 如何删除表?

发布于 2024-09-29 01:10:00 字数 246 浏览 2 评论 0原文

我添加了一张我认为需要的表格,但现在不再计划使用它。我应该如何删除该表?

我已经运行了迁移,因此该表位于我的数据库中。我认为rails生成迁移应该能够处理这个问题,但我还没有弄清楚如何处理。

我已经尝试过:

rails generate migration drop_tablename

但这只是生成了一个空迁移。

在 Rails 中删除表的“官方”方式是什么?

I added a table that I thought I was going to need, but now no longer plan on using it. How should I remove that table?

I've already run migrations, so the table is in my database. I figure rails generate migration should be able to handle this, but I haven't figured out how yet.

I've tried:

rails generate migration drop_tablename

but that just generated an empty migration.

What is the "official" way to drop a table in Rails?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(24

征棹 2024-10-06 01:10:00

您并不总是能够简单地生成迁移来获得您想要的代码。您可以创建一个空迁移,然后用您需要的代码填充它。

您可以在此处找到有关如何在迁移中完成不同任务的信息:

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

更具体地说,您可以使用以下方法了解如何删除表:

drop_table :table_name

You won't always be able to simply generate the migration to already have the code you want. You can create an empty migration and then populate it with the code you need.

You can find information about how to accomplish different tasks in a migration here:

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

More specifically, you can see how to drop a table using the following approach:

drop_table :table_name
2024-10-06 01:10:00

手动编写您的迁移。例如运行rails g migration DropUsers。

至于迁移的代码,我只是引用 Maxwell Holder 的帖子 Rails 迁移清单

BAD - running rake db:migrate 然后 rake db:rollback 将失败

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

好 - 揭示了迁移不应该可逆的意图

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

  def down
    fail ActiveRecord::IrreversibleMigration
  end
end

更好 - 实际上是可逆的

class DropUsers < ActiveRecord::Migration
  def change
    drop_table :users do |t|
      t.string :email, null: false
      t.timestamps null: false
    end
  end
end

Write your migration manually. E.g. run rails g migration DropUsers.

As for the code of the migration I'm just gonna quote Maxwell Holder's post 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 - reveals intent that migration should not be reversible

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

  def down
    fail ActiveRecord::IrreversibleMigration
  end
end

BETTER - is actually reversible

class DropUsers < ActiveRecord::Migration
  def change
    drop_table :users do |t|
      t.string :email, null: false
      t.timestamps null: false
    end
  end
end
乜一 2024-10-06 01:10:00

首先使用您想要的任何名称生成一个空迁移。这样做很重要,因为它会创建适当的日期。

rails generate migration DropProductsTable

这将在 /db/migrate/ 中生成一个 .rb 文件,如 20111015185025_drop_products_table.rb

现在编辑该文件,如下所示:

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

  def down
    raise ActiveRecord::IrreversibleMigration
  end
end

我添加的唯一内容是 drop_table :productsraise ActiveRecord::不可逆迁移

然后运行 ​​rake db:migrate ,它会为您删除该表。

First generate an empty migration with any name you'd like. It's important to do it this way since it creates the appropriate date.

rails generate migration DropProductsTable

This will generate a .rb file in /db/migrate/ like 20111015185025_drop_products_table.rb

Now edit that file to look like this:

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

  def down
    raise ActiveRecord::IrreversibleMigration
  end
end

The only thing I added was drop_table :products and raise ActiveRecord::IrreversibleMigration.

Then run rake db:migrate and it'll drop the table for you.

自控 2024-10-06 01:10:00

警告:执行此操作需要您自担风险,如 @z-atef 和 @< a href="https://stackoverflow.com/users/649006/nzifnab">nzifnab 正确指出,Rails 不会意识到这些更改,您的迁移序列填充失败,并且您的架构将与您的架构不同同事们。这只是作为本地修补开发的资源。


虽然这里提供的答案可以正常工作,但我想要一些更“直接”的东西,我在这里找到了它: 链接
首先进入 Rails 控制台:

$rails console

然后只需输入:

ActiveRecord::Migration.drop_table(:table_name)

完成,为我工作!

Warning: Do this at your own risk, as @z-atef and @nzifnab correctly point out, Rails will not be aware of these changes, your migration sequence fill fail and your schema will be different from your coworkers'. This is meant as a resource for locally tinkering with development only.


While the answers provided here work properly, I wanted something a bit more 'straightforward', I found it here: link
First enter rails console:

$rails console

Then just type:

ActiveRecord::Migration.drop_table(:table_name)

And done, worked for me!

岁月流歌 2024-10-06 01:10:00

您需要使用以下命令创建一个新的迁移文件

rails generate migration drop_table_xyz

,并在新生成的迁移文件(db/migration/xxxxxxx_drop_table_xyz)中写入 drop_table 代码,

drop_table :tablename

或者如果您想删除表而不进行迁移,只需打开 Rails 控制台

$ rails c

并执行以下命令

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

,或者您可以使用更简化的命令

ActiveRecord::Migration.drop_table(:table_name)

You need to to create a new migration file using following command

rails generate migration drop_table_xyz

and write drop_table code in newly generated migration file (db/migration/xxxxxxx_drop_table_xyz) like

drop_table :tablename

Or if you wanted to drop table without migration, simply open rails console by

$ rails c

and execute following command

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

or you can use more simplified command

ActiveRecord::Migration.drop_table(:table_name)
热风软妹 2024-10-06 01:10:00
  1. ruby-on-rails g 迁移 drop_users
  2. 编辑迁移
    class DropUsers < ActiveRecord::Migration
      def change
        drop_table :users do |t|
          t.string :name
          t.timestamps
        end
      end
    end
  1. rake db:migrate
  1. rails g migration drop_users
  2. edit the migration
    class DropUsers < ActiveRecord::Migration
      def change
        drop_table :users do |t|
          t.string :name
          t.timestamps
        end
      end
    end
  1. rake db:migrate
笑,眼淚并存 2024-10-06 01:10:00

简单而正式的方法是这样的:

  rails g migration drop_tablename

现在转到 db/migrate 并查找包含 drop_tablename 作为文件名的文件,并将其编辑为此。

    def change
      drop_table :table_name
    end

然后你需要

    rake db:migrate 

在控制台上运行。

The simple and official way would be this:

  rails g migration drop_tablename

Now go to your db/migrate and look for your file which contains the drop_tablename as the filename and edit it to this.

    def change
      drop_table :table_name
    end

Then you need to run

    rake db:migrate 

on your console.

祁梦 2024-10-06 01:10:00

我无法使其与迁移脚本一起使用,因此我继续使用此解决方案。使用终端输入 Rails 控制台:

rails c

Type

ActiveRecord::Migration.drop_table(:tablename)

它对我来说效果很好。这将删除以前的表。别忘了奔跑

rails db:migrate

I wasn't able to make it work with migration script so I went ahead with this solution. Enter rails console using the terminal:

rails c

Type

ActiveRecord::Migration.drop_table(:tablename)

It works well for me. This will remove the previous table. Don't forget to run

rails db:migrate
跨年 2024-10-06 01:10:00

我认为,要完全“官方”,您需要创建一个新的迁移,并将 drop_table 放入 self.up 中。 self.down 方法应该包含完整重新创建表的所有代码。据推测,该代码可以在您创建迁移时从 schema.rb 中获取。

放入代码来创建一个您知道不再需要的表似乎有点奇怪,但这将使所有迁移代码保持完整和“官方”,对吧?

我只是为一张需要放下的桌子做了这个,但说实话,我没有测试“放下”,也不知道为什么我会这样做。

I think, to be completely "official", you would need to create a new migration, and put drop_table in self.up. The self.down method should then contain all the code to recreate the table in full. Presumably that code could just be taken from schema.rb at the time you create the migration.

It seems a little odd, to put in code to create a table you know you aren't going to need anymore, but that would keep all the migration code complete and "official", right?

I just did this for a table I needed to drop, but honestly didn't test the "down" and not sure why I would.

无法言说的痛 2024-10-06 01:10:00

您只需从 Rails 控制台中删除一张桌子即可。
首先打开控制台,

$ rails c

然后将此命令粘贴到控制台中,

ActiveRecord::Migration.drop_table(:table_name)

table_name 替换为要删除的表。

您还可以直接从终端删除表格。只需进入应用程序的根目录并运行此命令

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

you can simply drop a table from rails console.
first open the console

$ rails c

then paste this command in console

ActiveRecord::Migration.drop_table(:table_name)

replace table_name with the table you want to delete.

you can also drop table directly from the terminal. just enter in the root directory of your application and run this command

$ rails runner "Util::Table.clobber 'table_name'"
奢望 2024-10-06 01:10:00

您可以按照指南中的方式回滚迁移:

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

生成迁移:

rails generate migration revert_create_tablename

编写迁移:

require_relative '20121212123456_create_tablename'

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

这样您还可以回滚并可用于恢复任何迁移

You can roll back a migration the way it is in the guide:

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

Generate a migration:

rails generate migration revert_create_tablename

Write the migration:

require_relative '20121212123456_create_tablename'

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

This way you can also rollback and can use to revert any migration

铁憨憨 2024-10-06 01:10:00

引发异常或尝试重新创建现在为空的表的替代方案 - 同时仍然启用迁移回滚、重做等 -

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

Alternative to raising exception or attempting to recreate a now empty table - while still enabling migration rollback, redo etc -

def change
  drop_table(:users, force: true) if ActiveRecord::Base.connection.tables.include?('users')
end
淡笑忘祈一世凡恋 2024-10-06 01:10:00

您不能简单地运行 drop_table :table_name,而是可以通过运行以下命令来创建空迁移:

然后,您可以将其添加到空迁移中:

class DropInstalls < ActiveRecord::Migration
  def change
    drop_table :installs
  end
end

然后在命令行中运行rails db:migrate,这将删除安装
此处找到了解决方案

You can't simply run drop_table :table_name, instead you can create an empty migration by running:
rails g migration DropInstalls

You can then add this into that empty migration:

class DropInstalls < ActiveRecord::Migration
  def change
    drop_table :installs
  end
end

Then run rails db:migrate in the command line which should remove the Installs table
The solution was found here

森林迷了鹿 2024-10-06 01:10:00

打开 Rails 控制台

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

Open you rails console

ActiveRecord::Base.connection.execute("drop table table_name")
平安喜乐 2024-10-06 01:10:00

ActiveRecord::Base.connection.drop_table :table_name

ActiveRecord::Base.connection.drop_table :table_name

拒绝两难 2024-10-06 01:10:00

我需要删除我们的迁移脚本以及表本身...

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

从终端窗口运行:

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

$ rails runner "Util::Table.clobber_all"

I needed to delete our migration scripts along with the tables themselves ...

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

from terminal window run:

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

or

$ rails runner "Util::Table.clobber_all"
莫相离 2024-10-06 01:10:00

如果有人正在寻找如何在 SQL 中做到这一点。

从终端输入 rails dbconsole

输入密码

在控制台中执行

USE db_name;

DROP TABLE table_name;

exit

请不要忘记从架构中删除迁移文件和表结构

if anybody is looking for how to do it in SQL.

type rails dbconsole from terminal

enter password

In console do

USE db_name;

DROP TABLE table_name;

exit

Please dont forget to remove the migration file and table structure from schema

铁轨上的流浪者 2024-10-06 01:10:00

有用文档

在迁移中,您可以通过以下方式删除表:

drop_table(table_name, **options)

options:

:force
设置为 :cascade 也可以删除依赖对象。默认为 false

:if_exists
设置为 true 仅删除表(如果存在)。默认为 false

示例:

  1. 为删除表创建迁移,例如我们要删除User

    rails g 迁移 DropUsers
    
    在进程 13189 中通过 Spring 预加载器运行
       调用活动记录
       创建 db/migrate/20211110174028_drop_users.rb
    
  2. 编辑迁移文件,在我们的例子中是db/migrate/20211110174028_drop_users.rb

    类 DropUsers < ActiveRecord::迁移[6.1]
      定义改变
        drop_table:用户,if_exist:true
      结尾
    结尾
    
  3. 运行迁移以删除 User

    rails db:migrate
    
    == 20211110174028 DropUsers:正在迁移================================
    -- drop_table(:users, {:if_exist=>true})
       -> 0.4607秒
    

Helpful documentation

In migration you can drop table by:

drop_table(table_name, **options)

options:

:force
Set to :cascade to drop dependent objects as well. Defaults to false

:if_exists
Set to true to only drop the table if it exists. Defaults to false

Example:

  1. Create migration for drop table, for example we are want to drop User table

    rails g migration DropUsers
    
    Running via Spring preloader in process 13189
       invoke  active_record
       create    db/migrate/20211110174028_drop_users.rb
    
  2. Edit migration file, in our case it is db/migrate/20211110174028_drop_users.rb

    class DropUsers < ActiveRecord::Migration[6.1]
      def change
        drop_table :users, if_exist: true
      end
    end
    
  3. Run migration for dropping User table

    rails db:migrate
    
    == 20211110174028 DropUsers: migrating ===============================
    -- drop_table(:users, {:if_exist=>true})
       -> 0.4607s
    
生来就爱笑 2024-10-06 01:10:00

Run

rake db:migrate:down VERSION=<version>

其中 是您要恢复的迁移文件的版本号。

例子:-

rake db:migrate:down VERSION=3846656238

Run

rake db:migrate:down VERSION=<version>

Where <version> is the version number of your migration file you want to revert.

Example:-

rake db:migrate:down VERSION=3846656238
森末i 2024-10-06 01:10:00

你能做的最好的方法就是

rails g migration Drop_table_Users

执行以下操作

rake db:migrate

the best way you can do is

rails g migration Drop_table_Users

then do the following

rake db:migrate
橘虞初梦 2024-10-06 01:10:00

删除表/迁移

运行:-
$rails 生成迁移 DropTablename

exp:- $rails 生成迁移 DropProducts

Drop Table/Migration

run:-
$ rails generate migration DropTablename

exp:- $ rails generate migration DropProducts

落花随流水 2024-10-06 01:10:00

如果你想删除一个特定的表,你可以这样做

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

,否则如果你想删除所有数据库,你可以这样做

$rails db:drop

if you want to drop a specific table you can do

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

otherwise if you want to drop all your database you can do

$rails db:drop
随波逐流 2024-10-06 01:10:00

运行此命令:-

rails g migration drop_table_name

然后:

rake db:migrate

或者如果您使用的是 MySql 数据库,那么:

  1. 使用数据库登录
  2. showdatabase;
  3. showtable;< /code>
  4. drop table_name;

Run this command:-

rails g migration drop_table_name

then:

rake db:migrate

or if you are using MySql database then:

  1. login with database
  2. show databases;
  3. show tables;
  4. drop table_name;
笔落惊风雨 2024-10-06 01:10:00

如果您想从架构中删除表,请执行以下操作--

rails db:rollback

If you want to delete the table from the schema perform below operation --

rails db:rollback
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文