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

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

我试过了:

rails generate migration drop_tablename

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

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


当前回答

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

至于迁移的代码,我将引用Maxwell Holder的帖子Rails migration Checklist

BAD—运行rake db:migrate and then rake db:rollback将失败

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

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

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

  def down
    fail ActiveRecord::IrreversibleMigration
  end
end

BETTER -实际上是可逆的

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

其他回答

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

rails db:rollback

你能做的最好的办法就是

rails g migration Drop_table_Users

然后执行以下操作

rake db:migrate

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

从终端输入rails dbconsole

输入密码

在控制台做

使用db_name;

DROP TABLE table_name;

exit

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

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

  rails g migration drop_tablename

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

    def change
      drop_table :table_name
    end

那你就得跑

    rake db:migrate 

在你的控制台。

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

至于迁移的代码,我将引用Maxwell Holder的帖子Rails migration Checklist

BAD—运行rake db:migrate and then rake db:rollback将失败

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

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

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

  def down
    fail ActiveRecord::IrreversibleMigration
  end
end

BETTER -实际上是可逆的

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