如何从我的Rails模型中删除一列?

我需要从我已经创build的轨道模型中删除几列,并在该模型中有一些行条目。 怎么做? 任何具有修改架构在轨道的细节的链接? 我正在使用rails版本3。

要删除数据库列,您必须生成迁移:

script/rails g migration RemoveColumns 

然后在self.up类的方法中,删除你的列:

 def self.up remove_column :table_name, :column_name end 

您也可以将它们添加回self.down类的方法中:

 def self.down add_column :table_name, :column_name, :type end 

Rails指南对此进行了更详细的介绍。

如果你知道你想删除的列,你可以使用约定:删除..从命名你的迁移时。 另外,您可以在运行迁移命令时包含列名称。

命令的forms:

 rails g migration Remove..From.. col1:type col2:type col3:type 

例如:

 rails g migration RemoveProjectIDFromProjects project_id:string 

生成以下迁移文件:

 class RemoveProjectIdFromProjects < ActiveRecord::Migration def self.up remove_column :projects, :project_id end def self.down add_column :projects, :project_id, :string end end 

通过命令备选作为Add ,只更改AddRemove

单栏:

 rails g migration RemoveColumnFromTable column:type 

多列:

 rails g migration RemoveColumn1AndColumn2FromTable column1:type colummn2:type