How to add primary_key (mysql+rails) on table which already has content

Posted by chetan
on Monday, October 22
You have a legacy database in which one table doesn't have primary_key defined. Now, activerecord needs a primary_key to run queries on this table. What do we do?

Create a migration and execute following SQL query

   execute "ALTER TABLE table_name 
            DROP COLUMN to_be_primary_key, 
            ADD COLUMN to_be_primary_key BIGINT(20) AUTO_INCREMENT NOT NULL FIRST,
            ADD PRIMARY KEY(to_be_primary_key);"