0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[Rails] foreign_key が必要となるケース

Posted at

概要

モデルの関連付けで foreign_key が必要となるケースについてまとめました。

foreign_keyが必要となるケース

前提として、Railsの規約を理解していきましょう。
Rails は CoC を設計思想として取り入れているため、基本的には以下のようなDB設計をするようにしてください。

  • RailsのActiveRecordはデフォルトで外部キーを<関連モデル>_id(例: user_id)として期待する

それを踏まえて、以下のようなケースで、foreign_key が必要となります。

  • モデルで期待する外部キー名が、実際のデータベースのカラム名と異なる場合
  • 例: PostモデルでUserモデルと関連付く外部キーに author_id を使用する場合

サンプルコード

class User < ApplicationRecord
  has_many :posts, foreign_key: :author_id, dependent: :destroy
end

class Post < ApplicationRecord
  belongs_to :user, foreign_key: :author_id
end

参照元テーブルと、参照先テーブルで foreign_keyの指定が必要になります。

まとめ

以上です。
どなたかの参考になれば幸いです。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?