45
44

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Rails 4.2 で MySQL の外部キー制約の作成と削除

Last updated at Posted at 2015-02-13

MySQL を DB に利用する場合で、外部キー制約を設定したい場合の方法。
Rails 4.2 から、標準で外部キー制約作成機能が追加された。

Ruby on Rails 4.2 Release notes

2.5 Foreign Key Support
The migration DSL now supports adding and removing foreign keys. They are dumped to schema.rb as well. At this time, only the mysql, mysql2 and postgresql adapters support foreign keys.

migration ファイルに下記のように書いてやればOK。

# add a foreign key to `articles.author_id` referencing `authors.id`
add_foreign_key :articles, :authors
 
# add a foreign key to `articles.author_id` referencing `users.lng_id`
add_foreign_key :articles, :users, column: :author_id, primary_key: "lng_id"
 
# remove the foreign key on `accounts.branch_id`
remove_foreign_key :accounts, :branches
 
# remove the foreign key on `accounts.owner_id`
remove_foreign_key :accounts, column: :owner_id

※追記

references をセットで指定するのを忘れるとエラーとなる。
まとめて定義する。

45
44
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
45
44

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?