11

I need to migrate an old mysql table like this:

Products
  name (string, primary_key)

to this schema:

Products
  id (integer, primary_key, auto_generated)
  name (unique)

I need the Products.id values populated in the new table. How can i write the rails migration file? I am using Rails 3.2.7

I have 2 problems now: 1. I can't find a method to remove primary key in ActiveRecord::Migration 2. I don't know how to generate values for newly added primary key.

4

2 回答 2

19

您可以在迁移中执行任意 SQL:

execute "ALTER TABLE `products` DROP PRIMARY KEY"

然后添加新列:

add_column :products, :id, :primary_key

看:

删除 MySQL 中的主键

如何将主键添加到rails中的表

http://thinkwhere.wordpress.com/2009/05/09/adding-a-primary-key-id-to-table-in-rails/

http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

于 2013-03-25T19:43:13.057 回答
14

如果您使用的是 Postgresql,则语法略有不同。

ALTER TABLE <table_name> DROP CONSTRAINT <table_name>_pkey;
于 2016-11-09T08:08:14.970 回答