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.
You can also add the FOREIGN KEY constraint to existing tables through ADD CONSTRAINT .
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.
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);
Foreigner works nicely for managing foreign keys.
Alternatively, you can just use the execute method to issue ALTER statements within your new migrations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With