如何更改Rails迁移文件中的主键? [英] How to change primary key in rails migration file?
问题描述
我需要像这样迁移一个旧的mysql表:
I need to migrate an old mysql table like this:
Products
name (string, primary_key)
此模式:
Products
id (integer, primary_key, auto_generated)
name (unique)
我需要在新表中填充的Products.id值。
如何编写Rails迁移文件?我正在使用Rails 3.2.7
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
我现在有2个问题:
1.我找不到在ActiveRecord :: Migration中删除主键的方法
2.我不知道如何为新添加的主键生成值。
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.
推荐答案
您可以执行任意操作迁移中的SQL:
You could execute arbitrary SQL in your migration:
execute "ALTER TABLE `products` DROP PRIMARY KEY"
,然后添加新列:
add_column :products, :id, :primary_key
请参阅:
http:// thinkwh ere.wordpress.com/2009/05/09/add-a-primary-key-id-to-table-in-rails/
< a href = http://api.rubyonrails.org/classes/ActiveRecord/Migration.html rel = noreferrer> http://api.rubyonrails.org/classes/ActiveRecord/Migration.html
这篇关于如何更改Rails迁移文件中的主键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!