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

查看:20
本文介绍了如何在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天全站免登陆