How to Add Foreign Key in Migration in Ruby on Rails
In Ruby on Rails migrations, you add a foreign key using the
add_foreign_key method inside the migration file. This method links one table's column to another table's primary key, ensuring referential integrity.Syntax
The add_foreign_key method has this basic syntax:
from_table: The table that contains the foreign key column.to_table: The table that the foreign key references (usually the primary key table).column(optional): The foreign key column name infrom_table. Defaults toto_tablesingularized with_id.options(optional): Additional options likeon_deleteornamefor the foreign key constraint.
ruby
add_foreign_key :from_table, :to_table, column: :foreign_key_column, on_delete: :cascade, name: "custom_fk_name"Example
This example shows how to add a foreign key from orders table to users table on the user_id column.
ruby
class AddUserForeignKeyToOrders < ActiveRecord::Migration[7.0] def change add_foreign_key :orders, :users end end
Output
Migration runs successfully and adds a foreign key constraint on orders.user_id referencing users.id
Common Pitfalls
Common mistakes when adding foreign keys include:
- Not having the foreign key column created before adding the foreign key constraint.
- Using the wrong column name if it differs from the Rails convention.
- Forgetting to handle
on_deletebehavior, which can cause errors when deleting referenced records.
Example of wrong and right usage:
ruby
class WrongForeignKey < ActiveRecord::Migration[7.0] def change # This will fail if orders.user_ref_id does not exist add_foreign_key :orders, :users, column: :user_ref_id end end class RightForeignKey < ActiveRecord::Migration[7.0] def change # Make sure the column exists and matches the name add_foreign_key :orders, :users, column: :user_id, on_delete: :cascade end end
Quick Reference
| Method | Description | Example |
|---|---|---|
| add_foreign_key | Adds a foreign key constraint | add_foreign_key :orders, :users |
| remove_foreign_key | Removes a foreign key constraint | remove_foreign_key :orders, :users |
| column option | Specify foreign key column name | add_foreign_key :orders, :users, column: :user_id |
| on_delete option | Set delete behavior (e.g., cascade) | add_foreign_key :orders, :users, on_delete: :cascade |
Key Takeaways
Use add_foreign_key in migrations to enforce database-level relationships.
Ensure the foreign key column exists before adding the foreign key constraint.
Specify the column option if your foreign key column name differs from Rails conventions.
Use on_delete option to control behavior when referenced records are deleted.
Always test migrations to confirm foreign keys are added correctly.