Railsでprimary_keyとforeign_keyの両方を指定して主キーではないカラムで関連付けする
こんな関連付けのモデルがあったとして
class Atable < ApplicationRecord has_one :btable has_one :ctable end class Btable < ApplicationRecord belongs_to :atable end class Ctable < ApplicationRecord belongs_to :atable end
bからcを呼び出すのに
Btable.find(1).atable.ctable
としなきゃいけないのはだるい
btables.atable_id = ctables.atable_id
の条件で関連付けしたい
primary_key, foreign_keyを両方指定して関連付けをする
こうなる
class Atable < ApplicationRecord has_one :btable has_one :ctable end class Btable < ApplicationRecord belongs_to :atable has_one :ctable, primary_key: :atable_id, foreign_key: :atable_id end class Ctable < ApplicationRecord belongs_to :atable belongs_to :btable, primary_key: :atable_id, foreign_key: :atable_id end