Foreign Keys
- Support in
Rails 4.2+
- Referential integrity
- In order to make the foreign key work, you need the corresponding reference
rails g model
model_name ref_model:references
rails g model menu_category name:string description:string menu:references
# generate
class CreateMenuCategories < ActiveRecord::Migration
def change
create_table :menu_categories do |t|
t.string :name
t.string :description
t.references :menu, index: true, foreign_key: true
t.timestamps null: false
end
end
end
rails g migration
AddXxxRefToTable
ref_model_name:references
rails g migration AddMenuRefToMenuCategories menu:references
# generate
class AddMenuRefToMenuCategories < ActiveRecord::Migration
def change
add_reference :menu_categories, :menu, index: true, foreign_key: true
end
end
add_foreign_key
:create a new migration to manually add foreign key for existing reference
class ... < ActiveRecord::Migration
def change
add_foreign_key :table_name, :model_name
end
end