LoginSignup
118
102

More than 5 years have passed since last update.

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

Last updated at Posted at 2016-03-20

「同じ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] 複数の外部キーがある場合のアソシエーション

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