Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add foreign key constraints to existing tables in Ruby on Rails (MySQL)

What's the best way to add foreign keys to my existing tables in Rails with an underlying MySQL database? clearly the solution should be done in a migration, as I want this versioned. Otherwise I'd create the constraints myself.

I can't seem to find one, conducive response to they above. Again, the tables have already been created with previous migrations. I'm just going back now and adding referential integrity wherever it's applicable.

like image 593
randombits Avatar asked Apr 15 '10 01:04

randombits


People also ask

Can I add a foreign key constraint to an existing table with data?

You can also add the FOREIGN KEY constraint to existing tables through ADD CONSTRAINT .

How do I add a foreign key in Ruby on Rails?

If you want you can always use add_index on the fields that you want as foreign keys. Or you can write your migrations in SQL or perhaps even force rails to do the foreign keys somehow. But the thing is you won't even look for a way to do it if you don't know rails is not doing itin the first place.

How do I add a foreign key constraint in SQL Server for existing table?

The syntax for creating a foreign key using an ALTER TABLE statement in SQL Server (Transact-SQL) is: ALTER TABLE child_table ADD CONSTRAINT fk_name FOREIGN KEY (child_col1, child_col2, ... child_col_n) REFERENCES parent_table (parent_col1, parent_col2, ... parent_col_n);


1 Answers

Foreigner works nicely for managing foreign keys.

Alternatively, you can just use the execute method to issue ALTER statements within your new migrations.

like image 50
Dave Pirotte Avatar answered Sep 27 '22 00:09

Dave Pirotte