【问题标题】:Rails 3.1 add columns with change_table migrationRails 3.1 使用 change_table 迁移添加列
【发布时间】:2011-10-09 06:00:30
【问题描述】:

我有一张名为profiles 的表,其中包含一些列。

现在我希望使用 rails 3.1 中的change-方法向该表添加几列。我使用以下代码创建了一个迁移:

def change
  change_table :profiles do |t|
    t.string :photo
    t.string :name
    t.references :user
  end
end

迁移工作完美,但是当我想回滚时,我得到了

SQLite3::SQLException: duplicate column name: photo: ALTER TABLE "profiles" ADD "photo" varchar(255)

有什么想法吗?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3.1


    【解决方案1】:

    在 Rails 3.1 中用于添加列的自动生成迁移格式为:

    class AddColumnToTable < ActiveRecord::Migration
      def change
        add_column :table, :column, :type
      end
    end
    

    也许试试那个语法?

    【讨论】:

    • 用 add_column 添加引用怎么样?我想我可以这样做:stackoverflow.com/questions/493777/… 但是能够以某种方式直接在迁移中添加它会更加灵活。
    • @martnu:添加引用只是将整数类型的 ID 字段添加到表中 - 您可以使用 add_column :profiles, :user_id, :integer 复制它。
    • reference 还在assoc_id 列上添加了一个索引,这很有用。
    • 根据来源,没有自动添加这样的索引。当然,您当然可以手动添加一个。
    【解决方案2】:

    看来您需要告诉迁移如何恢复自身:

    def change
      change_table :profiles do |t|
        t.string :photo
        t.string :name
        t.references :user
      end
    
      reversible do |dir|
        dir.down do
          remove_column :profiles, :photo
          remove_column :profiles, :name
          remove_column :profiles, :user_id
        end
      end
    end
    

    更多信息请参见http://guides.rubyonrails.org/migrations.html#using-reversible

    或者,您可以尝试使用仍然可用的旧 up 和 down 方法,如下所示:

    def up
      change_table :profiles do |t|
        t.string :photo
        t.string :name
        t.references :user
      end
    end
    
    def down
      remove_column :profiles, :photo
      remove_column :profiles, :name
      remove_column :profiles, :user_id
    end
    

    更多关于上/下的信息:http://guides.rubyonrails.org/migrations.html#using-the-up-down-methods

    【讨论】:

      猜你喜欢
      • 2022-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-24
      • 1970-01-01
      • 2017-02-17
      • 2014-05-13
      • 1970-01-01
      相关资源
      最近更新 更多