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

后端 未结 4 1426
眼角桃花
眼角桃花 2021-02-06 22:07

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 recre

4条回答
  •  后悔当初
    2021-02-06 23:08

    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.

提交回复
热议问题