Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 716
Jonathan Chiu Avatar asked Mar 16 '11 16:03

Jonathan Chiu


People also ask

How do I add a primary key without dropping the table?

However, you can only use the ALTER TABLE statement to create a primary key on column(s) that are already defined as NOT NULL. If the column(s) allow NULL values, you will not be able to add the primary key without dropping and recreating the table.

What is primary key in rails?

Primary keys - By default, Active Record will use an integer column named id as the table's primary key ( bigint for PostgreSQL and MySQL, integer for SQLite). When using Active Record Migrations to create your tables, this column will be automatically created.

Can we add primary key existing table with data in Oracle?

SQL PRIMARY KEY on ALTER TABLE. ADD CONSTRAINT PK_Person PRIMARY KEY (ID,LastName); Note: If you use ALTER TABLE to add a primary key, the primary key column(s) must have been declared to not contain NULL values (when the table was first created).


2 Answers

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.

like image 168
Ryan Avatar answered Sep 30 '22 00:09

Ryan


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 
like image 25
Andrew Avatar answered Sep 30 '22 00:09

Andrew