[Rails] 同じmodelを参照する外部キーを一つのmodelでもつ方法


「同じmodelを参照する外部キーをもつ」とは、例えば「ユーザ間取引」とか。その場合、売り手と買い手の2つのユーザを参照しなければならない。railsのデフォルトでは、外部キーを表す命名規則が${model名}_idと決まっているため、同じmodelを参照する外部キーがそのままでは設定できない。
この様な場合、belongs_to/has_manyforeign_keyオプションを使って、それぞれ外部キー設定してあげればよい。
まず、下記のようなmodelとする。

Transaction model
seller_id (User modelの外部キー)
buyer_id (User modelの外部キー)
User model
nameとか
emailとか

この場合、modelのbelongs_to/has_manyforeign_keyを明示的に指定する。
これで、transaction.sellerで売り手の情報が、transaction.buyerで買い手の情報が、そしてuser.seller_transactions/user.buyer_transactionsで取引の情報が取得できる。

models/transaction.rb
belongs_to :buyer, class_name: 'User', :foreign_key => 'buyer_id'
belongs_to :seller, class_name: 'User', :foreign_key => 'seller_id'
models/user.rb
has_many :buyer_transactions, class_name: 'Transaction', :foreign_key => 'buyer_id'
has_many :seller_transactions, class_name: 'Transaction', :foreign_key => 'seller_id'

参考

belongs_to
[Rails3] 複数の外部キーがある場合のアソシエーション