通过Rails迁移删除数据库表列的语法是什么?


当前回答

在模型中将列标记为忽略

class MyModel < ApplicationRecord
  self.ignored_columns = ["my_field"]
end

生成迁移

$ bin/rails g migration DropMyFieldFromMyModel

编辑迁移

class DropMyFieldFromMyModel < ActiveRecord::Migration[6.1]
  def change
    safety_assured { remove_column :my_table, :my_field }
  end
end

运行迁移

$ bin/rails db:migrate

其他回答

在模型中将列标记为忽略

class MyModel < ApplicationRecord
  self.ignored_columns = ["my_field"]
end

生成迁移

$ bin/rails g migration DropMyFieldFromMyModel

编辑迁移

class DropMyFieldFromMyModel < ActiveRecord::Migration[6.1]
  def change
    safety_assured { remove_column :my_table, :my_field }
  end
end

运行迁移

$ bin/rails db:migrate

这样做;

rails g migration RemoveColumnNameFromTables column_name:类型

即rails g migration RemoveTitleFromPosts title:字符串

无论如何,最好考虑停机时间以及因为ActiveRecord在运行时缓存数据库列,所以如果你删除一列,它可能会导致异常,直到你的应用程序重新启动。

参考:强迁移

给出下面的命令,它将自己添加到迁移文件中

rails g migration RemoveColumnFromModel

运行以上命令后,您可以检查迁移文件remove_column代码必须自己添加到那里

然后迁移数据库

rake db:migrate

Rails 5和6的清晰和简单的说明

警告:您将丢失数据。 警告:下面的指令是针对普通迁移的。对于复杂的迁移,例如数百万行,读/写dbs,集群,这个建议不适合你:


1. 创建迁移

在终端运行如下命令:

rails生成迁移remove_fieldname_from_tablename fieldname:fieldtype(根据约定,表名为复数形式。请在这里查看文档。)

示例:rails g migration RemoveAcceptedFromQuotes accepted:boolean

2. 检查迁移

# db/migrate/20190122035000_remove_accepted_from_quotes.rb
class RemoveAcceptedFromQuotes < ActiveRecord::Migration[5.2]
  # with rails 5.2 you don't need to add a separate "up" and "down" method.
  def change
    remove_column :quotes, :accepted, :boolean
  end
end

3.运行迁移

Rake db:migrate or rails db:migrate(它们都是相同的)

....然后你就可以去比赛了!

你可以尝试以下方法:

remove_column :table_name, :column_name

(官方文档)