如何更改Rails迁移文件中的主键? [英] How to change primary key in rails migration file?

查看:53
本文介绍了如何更改Rails迁移文件中的主键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要像这样迁移一个旧的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

请参阅:

删除MySQL中的主键

如何添加导轨中表的主键

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆