LoginSignup
1
0

More than 3 years have passed since last update.

Railsの関連付けのオプションを軽くまとめた(foreign_key、primary_key)

Last updated at Posted at 2020-10-07

背景

テーブル同士の関連付けで、外部キーを変更するときにちょっとハマったので。

テーブル設計

products
id
number
price
features
id
product_number
etc...

やりたいこと

productsのnumberとfeaturesのproduct_numberで関連付けたい。

解説

コード

has_one :feature, foreign_key: "number", primary_key: "product_number"
belongs_to :product, foreign_key: "product_number", primary_key: "number"

つまり、product側からfeatureを参照するときは、productのnumberとfeatureのproduct_numberが等しいレコードが紐付く。
逆も同様。

まとめ

foreign_key 外部キーを指定(参照元のテーブルのカラムを指定)。デフォルトはhogehoge_id。
primary_key 別のテーブルを参照するときに用いるカラム(参照先のテーブルのカラムを指定)を指定。デフォルトでid。
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