如何向 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在迁移中添加主键的命令是:
add_column :my_table, :id, :primary_key
但是,您问题的措辞表明您的表已经有一个自动增量列。除非我弄错了,否则有几种 DBMS 不允许在一张表上有多个自动增量列。
如果您已经有一个自动增量列,并且您确实想使用该列作为主键,只需将以下内容添加到您的模型中:
set_primary_key "my_existing_column"
或者在 Rails 的更新版本中:
self.primary_key = "my_existing_column"
如果您已经有一个自动增量列并且无法将其用作主键,那么您可能会不走运。
The command to add a primary key in a migration is:
add_column :my_table, :id, :primary_key
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"
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.
如果由于某种原因您创建了一个带有自定义
id
字段的表,但忘记将id
设置为主键,则需要运行迁移来创建主键约束。以下内容针对 PostgreSQL 数据库进行了测试:If for some reason you created a table with a custom
id
field, but forgot to setid
as the primary key, you need to run a migration to create the primary key constraint. The following was tested against a PostgreSQL database:我知道在 mySQl 中您可以添加一个具有默认增量值的列。
如果您添加这一点,那么每一行都将具有唯一的 int 值(任何新行都会获得比最后添加的行大 1 的 int 值)
您可以添加此列并将其设置为主键。
I know in mySQl that you can add a column that has a default increment value.
If you add that then each row will have a unique int value (and any new row will get a int value 1 greater then the last row added)
You could add this column and set it as a primary key.
这是一个现在需要成为具有主键的真实模型的连接表吗?如果是这样,最好的办法是创建新表并将数据复制到其中。
Was this a join table that now needs to become a real model with a primary key? If so, your best bet is to create the new table and copy the data into it.