簡體   English   中英

Rails 3.1 使用 change_table 遷移添加列

[英]Rails 3.1 add columns with change_table migration

我有一張名為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)

任何想法為什么?

在 Rails 3.1 中添加列的自動生成遷移格式如下:

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

也許試試那個語法?

看起來您需要告訴遷移如何恢復自身:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM