我添加了一个我认为我将需要的表格,但现在不再计划使用它。我该如何移除那张桌子?

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

我试过了:

rails generate migration drop_tablename

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

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


当前回答

Rails迁移drop_users 编辑迁移

    class DropUsers < ActiveRecord::Migration
      def change
        drop_table :users do |t|
          t.string :name
          t.timestamps
        end
      end
    end

rake db: migrate

其他回答

如果要从模式中删除表,请执行下面的操作——

rails db:rollback

你可以按照指南中的方式回滚一次迁移:

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

通过这种方式,您还可以回滚并用于恢复任何迁移

帮助文档

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

drop_table(table_name, **options)

选项:

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

: if_exists 设置为true仅在表存在时删除它。默认为false

例子:

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 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 Run migration for dropping User table rails db:migrate == 20211110174028 DropUsers: migrating =============================== -- drop_table(:users, {:if_exist=>true}) -> 0.4607s

Run

rake db:migrate:down VERSION=<version>

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

例子:-

rake db:migrate:down VERSION=3846656238

ActiveRecord:: Base.connection。drop_table: table_name