外部キー制約

 

<外部キー制約とは>

データベース側の項目に付ける制限

好きに値を入れられないようになっており、別テーブルの項目から値を選んで入れるように指定する。

 

 

今回の場合はuserテーブルとboardテーブルが依存関係にある。

FOREIGN KEY 制約の設定は子テーブル側で行う。

なので、今回は子テーブルである、db/migrate下のxxxx_create_boards.rb

foreign_key: trueを記載する。

 

def change
create_table :boards do |t|
t.string :title, null: false
t.text :body, null: false
t.references :user, foreign_key: true, null: false

t.timestamps
end
end

 

 

参考にした資料

https://dev.mysql.com/doc/refman/5.6/ja/create-table-foreign-keys.html