1
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 - id 以外で belongs_to / has_many の関連付けをしたいが、 primary key が重複する時の書き方

Last updated at Posted at 2025-05-15
  • foreign_key
  • primary_key

とあわせて optional: true を指定すれば、テーブル中で外部キーの値が重複していてもエラーを起こさず許容してくれるようだ

子クラス

class Book < ApplicationRecord
    belongs_to :author, foreign_key: :code, primary_key: :author_code, optional: true

親クラス

class Author < ApplicationRecord
  has_many :books, foreign_key: :authori_code, primary_key: :code
1
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
1
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?