2011-07-20 63 views
5

我有一个表叫profiles一些列。的Rails 3.1添加列与change_table迁移

现在我想用钢轨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) 

任何想法,为什么?

回答

5

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

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

也许尝试语法?

+0

什么?我想我可以这样做:http://stackoverflow.com/questions/493777/add-column-for-references-rails/493802#493802但它会更灵活,能够直接在迁移中添加它不知何故。 – martnu

+0

@martnu:添加引用只是增加了整数类型的ID字段的表 - 你可以用'add_column复制它:型材,:USER_ID,:integer'。 – sevenseacat

+0

'reference'还在'assoc_id'列中增加了一个索引,这很有用。 – Jeriko

0

看起来你需要告诉迁移如何恢复自己:

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

或者你可以尝试使用旧的向上和向下的方法,其仍然可以像这样:

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 

更多关于上/下位置:关于增加与add_column参考http://guides.rubyonrails.org/migrations.html#using-the-up-down-methods