foreign_key 外部キーを指定する
使用可能な関連付け
belongs_to
has_and_belongs_to_many
has_many
has_one
対となる関連に指定するオプション
なし
概要
Railsの命名規則に則った実装をしていれば不要であるが、なんらかの理由で外部キーがデフォルトと異なる場合に指定する。
# 外部キーが命名規則に則っていない場合
class Author < ApplicationRecord
belongs_to :profile, foreign_key: :prof_id
end
class Profile < ApplicationRecord
has_one :author, foreign_key: :prof_id
end
# 外部キーが命名規則に則っておらず、関連名も外部キーに合わせている場合
class Author < ApplicationRecord
# prof_idという外部キーを持つ
belongs_to :prof, class_name: 'Profile'
end
class Profile < ApplicationRecord
# Author側で持っているProfileの外部キーを指定する
has_one :author, foreign_key: :prof_id
end
# 外部キーは命名規則に則っているが、関連名だけ異なる場合
class Author < ApplicationRecord
belongs_to :prof, foreign_key: :profile_id, class_name: 'Profile'
end
class Profile < ApplicationRecord
has_one :author
end
# 外部キー名、関連名、関連先クラス名がバラバラな場合
class Author < ApplicationRecord
belongs_to :p, foreign_key: :prof_id, class_name: 'Profile'
end
class Profile < ApplicationRecord
has_one :author, foreign_key: :prof_id
end