Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change primary key in rails migration file?

I need to migrate an old mysql table like this:

Products
  name (string, primary_key)

to this schema:

Products
  id (integer, primary_key, auto_generated)
  name (unique)

I need the Products.id values populated in the new table. How can i write the rails migration file? I am using Rails 3.2.7

I have 2 problems now: 1. I can't find a method to remove primary key in ActiveRecord::Migration 2. I don't know how to generate values for newly added primary key.

like image 967
Wint Avatar asked Mar 25 '13 18:03

Wint


2 Answers

You could execute arbitrary SQL in your migration:

execute "ALTER TABLE `products` DROP PRIMARY KEY"

and then add the new column:

add_column :products, :id, :primary_key

See:

Remove Primary Key in MySQL

how to add a primary key to a table in rails

http://thinkwhere.wordpress.com/2009/05/09/adding-a-primary-key-id-to-table-in-rails/

http://api.rubyonrails.org/classes/ActiveRecord/Migration.html

like image 80
Jordan Allan Avatar answered Oct 13 '22 10:10

Jordan Allan


If you're on Postgresql, the syntax is slightly different.

ALTER TABLE <table_name> DROP CONSTRAINT <table_name>_pkey;
like image 27
jlfenaux Avatar answered Oct 13 '22 09:10

jlfenaux