0
0

More than 3 years have passed since last update.

belongs_to関連付けのforeign_keyオプション(Rails Guide自分用訳)

Last updated at Posted at 2021-01-13

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