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

后端 未结 4 1423
眼角桃花
眼角桃花 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:09

    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
    

提交回复
热议问题