Ruby-on-rails 如何从我的 Rails 模型中删除一列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3948804/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:24:00  来源:igfitidea点击:

How to remove a column from my Rails model?

ruby-on-railsruby-on-rails-3

提问by Hemanth

I need to remove a few columns from my rails model which i already created and have some row entries in that model. How to do it? Any links which has details for modifying the schema in rails ? I'm using rails version 3.

我需要从我已经创建的 Rails 模型中删除几列,并在该模型中有一些行条目。怎么做?任何包含在 rails 中修改架构的详细信息的链接?我正在使用 Rails 版本 3。

回答by Jason stewart

To remove a database column, you have to generate a migration:

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

script/rails g migration RemoveColumns

Then in the self.up class method, remove your columns:

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

def self.up
  remove_column :table_name, :column_name
end

You may want to add them back in the self.down class method as well:

您可能还想将它们添加回 self.down 类方法中:

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

The Rails Guidefor this goes into much more detail.

Rails的指南此进入更多的细节。

回答by slm

If you know the columns you want to remove you can use the convention: Remove..From.. when naming your migrations. Additionally you can include the column names when running the migration command.

如果您知道要删除的列,则可以在命名迁移时使用约定:Remove...From...。此外,您可以在运行迁移命令时包含列名称。

The form of the command:

命令的形式:

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

For example:

例如:

rails g migration RemoveProjectIDFromProjects project_id:string

generates the following migration file:

生成以下迁移文件:

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

  def self.down
    add_column :projects, :project_id, :string
  end
end

回答by Gediminas

Via command alternative as Add, only change Addto Remove:

通过命令替代 as Add,只更改AddRemove

Single Column:

单列:

rails g migration RemoveColumnFromTable column:type

Multiple Columns:

多列:

rails g migration RemoveColumn1AndColumn2FromTable column1:type colummn2:type