How do I retroactively add a primary key to my table in rails?

ⅰ亾dé卋堺 提交于 2019-12-03 14:36:01

问题


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?


回答1:


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.




回答2:


If for some reason you created a table with a custom id field, but forgot to set id as the primary key, you need to run a migration to create the primary key constraint. The following was tested against a PostgreSQL database:

class AddPrimaryKeyConstraintToFoobars < ActiveRecord::Migration
  def up
    execute "ALTER TABLE foobars ADD PRIMARY KEY (id);"
  end

  def down
    execute "ALTER TABLE foobars DROP CONSTRAINT foobars_pkey;"
  end
end



回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/5328528/how-do-i-retroactively-add-a-primary-key-to-my-table-in-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!