如何在Rails中向表追溯添加主键? [英] How do I retroactively add a primary key to my table in rails?

查看:105
本文介绍了如何在Rails中向表追溯添加主键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个没有主键的表(:id => false),但是现在它又回到了我的屁股.

I've created a table without a primary key (:id => false), but now it has come back to bite my ass.

我的应用程序已经在生产中,不能随便删除它并重新创建一个.

My app is already in production and I can't just drop it and recreate another one.

是否可以运行迁移以将另一个自动增量主键列添加到我的表中?

Is there a way to run a migration to add another auto increment primary key column to my table?

推荐答案

在迁移中添加主键的命令是:

The command to add a primary key in a migration is:

add_column :my_table, :id, :primary_key

但是,您的问题的措词表明您的表已经具有一个自动增量列.除非我没有记错,否则有几种DBMS不允许在一个表上使用多个自动递增列.

However, the wording of your question suggests that your table already has an auto-increment column. Unless I'm mistaken, there are several DBMS that do not allow more than one auto-increment column on a table.

如果您确实已经有一个自动增量列,并且您实际上想将该列用作主键,只需将以下内容添加到模型中即可:

If you DO already have an auto-increment column and you actually want to use that column as your primary key, just add the following to your model:

set_primary_key "my_existing_column"

或者在最新版本的Rails中:

Or in more recent versions of Rails:

self.primary_key = "my_existing_column"

如果您已经有一个自动增量列,并且不能将其用作主键,则可能不走运.

In the case that you already have an auto-increment column and you can't use that as the primary key, you may be out of luck.

这篇关于如何在Rails中向表追溯添加主键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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