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

Mysql 删除数据库中表中的多个列。(轨道),mysql,ruby-on-rails,Mysql,Ruby On Rails,删除本地数据库中的多个列时遇到问题 我的表名是“customers”,在该表中,我试图删除的两列是“phone”和“fax” 我一直在尝试这方面的东西 class CustomerCleanup < ActiveRecord::Migration def change_table(:customers) do |t| t.remove :fax, :phone end end end class CustomerCleanup

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

我的表名是“customers”,在该表中,我试图删除的两列是“phone”和“fax”

我一直在尝试这方面的东西

class CustomerCleanup < ActiveRecord::Migration
  def change_table(:customers) do |t|
      t.remove :fax, :phone
    end
  end
end
class CustomerCleanup
但我仍然收到一个语法错误,声明“unexpected tSYMBEG expecting”)

我已经看了…中的例子,我也试过了,结果得到了同样的错误

class CustomerCleanup < ActiveRecord::Migration
  def change_table(:customers) do |t|
      t.remove :fax
      t.remove :phone
    end
  end
end
class CustomerCleanup
有人知道我做错了什么吗?

你试过:

def change
  remove_column :customers, :fax
  remove_column :customers, :phone
end

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

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

如果要通过运行迁移从任何表中删除列,请尝试以下操作

rails g migration remove_columns_from_table_name field_name:datatype field_name:datatype
表\u名称替换为要从中删除列的表,将字段\u名称:数据\u类型替换为要删除的列和列的数据类型

迁移文件如下所示

class RemoveColumnsFromTableName < ActiveRecord::Migration
  def change
    remove_column :table_name, :field_name, :data_type
    remove_column :table_name, :field_name, :data_type
  end
end
ActiveRecord::Migration.remove_column :table_name, :column_name 
您还可以通过如下操作直接从
rails控制台中删除列

class RemoveColumnsFromTableName < ActiveRecord::Migration
  def change
    remove_column :table_name, :field_name, :data_type
    remove_column :table_name, :field_name, :data_type
  end
end
ActiveRecord::Migration.remove_column :table_name, :column_name 

我知道这是一个老生常谈的问题,并且有一个明确的答案,但是没有人解决您的实际语法错误。您正在将方法定义与更改表调用相结合。正确的代码应为:

class CustomerCleanup < ActiveRecord::Migration
  def change
    change_table(:customers) do |t|
      t.remove :fax
      t.remove :phone
    end
  end
end
class CustomerCleanup
您可以使用


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

您使用的Rails版本是什么?
remove\u column:myTable,:col1
@Jerrod我使用的是2.1。6@Drew我是否必须删除列:myTable,:col1,:col2
?我有不止一件事要澄清,也许是@Jerrod问这个版本的原因。我相信Rails 4已经改变了。你知道有没有一种真正的方法来循环它们吗?我这样问是因为我实际上喜欢删除6件东西。你的意思是:
[:传真,:电话,:某物]。每个{列|删除{列:客户,列}