[Rails] 同じmodelを参照する外部キーを一つのmodelでもつ方法
「同じmodelを参照する外部キーをもつ」とは、例えば「ユーザ間取引」とか。その場合、売り手と買い手の2つのユーザを参照しなければならない。railsのデフォルトでは、外部キーを表す命名規則が${model名}_id
と決まっているため、同じmodelを参照する外部キーがそのままでは設定できない。
この様な場合、belongs_to
/has_many
のforeign_key
オプションを使って、それぞれ外部キー設定してあげればよい。
まず、下記のようなmodelとする。
Transaction model |
---|
seller_id (User modelの外部キー) |
buyer_id (User modelの外部キー) |
User model |
---|
nameとか |
emailとか |
この場合、modelのbelongs_to
/has_many
でforeign_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'
参考
Author And Source
この問題について([Rails] 同じmodelを参照する外部キーを一つのmodelでもつ方法), 我々は、より多くの情報をここで見つけました https://qiita.com/takeoverjp/items/bb56d6a8eae191cd3732著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .