Railsの慣例では、相手のモデルを指す外部キーを保持しているjoinテーブル上のカラム名については、そのモデル名にサフィックス_idを追加した関連付け名
が使われることを前提とします。:foreign_keyオプションを使えば、外部キーの名前を直接指定できます。
By convention, Rails assumes that the column used to hold the foreign key on this model is the name of the association with the suffix _id added
. The :foreign_key option lets you set the name of the foreign key directly:
- 自分用訳
Railsの慣例では、このモデルの外部キーを保持するカラム名は、関連付け名に接尾辞の_idを付けたもの
と、想定している。:foreign_keyオプションを使えば、外部キーを保持するカラム名を指定することができる。
Railsが慣例で想定しているforeign_key
class Book < ApplicationRecord
belongs_to :author(, foreign_key: author_id)
end
関連付け名に__idをつけたforeign_keyをRailsは想定しているので、下の例では :foreign_keyオプションが必要となる。
class Book < ApplicationRecord
belongs_to :author, class_name: "Patron",
foreign_key: "patron_id"
end