代码之家  ›  专栏  ›  技术社区  ›  Hemanth

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

  •  49
  • Hemanth  · 技术社区  · 14 年前

    怎么做?有没有在rails中修改模式的详细信息的链接? 我正在使用rails版本3。

    3 回复  |  直到 14 年前
        1
  •  58
  •   Tim    9 年前

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

    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 Guide

        2
  •  42
  •   Marcelo De Polli    10 年前

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

    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
    
        3
  •  6
  •   leo.fcx    8 年前

    Add ,仅更改 添加 Remove :

    单列:

    rails g migration RemoveColumnFromTable column:type
    

    多列:

    rails g migration RemoveColumn1AndColumn2FromTable column1:type colummn2:type