删除数据库中表中的多个列。(铁轨)

kdw*_*r89 4 mysql ruby-on-rails

我在删除本地数据库中的多个列时遇到问题。

我的表名是“客户”,在该表中,我要删除的两列是“电话”和“传真”

我一直在尝试一些类似的方法

class CustomerCleanup < ActiveRecord::Migration
  def change_table(:customers) do |t|
      t.remove :fax, :phone
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

但我继续收到语法错误,指出“意外的tSYMBEG预期为')'

我看过这里的示例...,我也尝试过这样做,只是得到了同样的错误

class CustomerCleanup < ActiveRecord::Migration
  def change_table(:customers) do |t|
      t.remove :fax
      t.remove :phone
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

有人知道我在做什么错吗?

Tob*_*obi 9

您可以使用该方法在单个语句中删除多个列remove_columns

def up
  remove_columns :customers, :fax, :phone
end
Run Code Online (Sandbox Code Playgroud)

但是,down如果您希望能够回滚,则必须定义一个单独的方法。


OzB*_*rry 6

我知道这是一个古老的问题,答案很明显,但是没人能解决您的实际语法错误。您正在将方法定义与change_table调用结合在一起。正确的代码应为:

class CustomerCleanup < ActiveRecord::Migration
  def change
    change_table(:customers) do |t|
      t.remove :fax
      t.remove :phone
    end
  end
end
Run Code Online (Sandbox Code Playgroud)


Lon*_*yen 5

你有没有尝试过:

def change
  remove_column :customers, :fax
  remove_column :customers, :phone
end
Run Code Online (Sandbox Code Playgroud)

如果您使用的Rails版本低于3.x

def self.up
 remove_column :customers, :fax
 remove_column :customers, :phone
end

def self.down
  # do something on rollback here or just do nothing
end
Run Code Online (Sandbox Code Playgroud)


far*_*lar 5

如果您想通过运行迁移从任何表中删除列,请尝试此操作

rails g migration remove_columns_from_table_name field_name:datatype field_name:datatype
Run Code Online (Sandbox Code Playgroud)

将table_name替换为要从中删除列的表,并将field_name:data_type 替换为要删除的列和列的数据类型。

迁移文件将如下所示

class RemoveColumnsFromTableName < ActiveRecord::Migration
  def change
    remove_column :table_name, :field_name, :data_type
    remove_column :table_name, :field_name, :data_type
  end
end
Run Code Online (Sandbox Code Playgroud)

然后运行迁移

rake db:migrate
Run Code Online (Sandbox Code Playgroud)

rails console您还可以通过执行以下操作直接删除列

ActiveRecord::Migration.remove_column :table_name, :column_name 
Run Code Online (Sandbox Code Playgroud)