目次
外部キー制約について
class CreateProducts < ActiveRecord::Migration[7.0]
def change
create_table :goriras, comment: " ゴリラ" do |t|
t.references :animal, foreign_key: true, comment: "動物id" ## ここ
t.string :name, comment: "ゴリラ名"
t.text :self_introduction, commnet: "自己紹介文"
t.timestamps
end
end
end
t.referencesを使用するときの注意点
t.references :animal, foreign_key: true
この記述によって外部キー制約をつけることができる。ちなみにt.references
と書くだけでは外部キー制約は付与されないので、`foreign_key: true
‘と書く必要がある。これを書くことによって、外部キー制約とプラスでindexをanimal_idにはることができる。
ちなみに_idとする必要はない
そうそう、t.referenceを使用する時は、animal_idと書く必要はなく、amnimlで済むので注意。
Railsガイドはこちら
Active Record の関連付け - Rails...


Active Record の関連付け - Railsガイド
Active Recordが提供するすべての関連付け機能(アソシエーション)について解説します。