has_many, has_one 与复合外键的关联

问题描述

我正在努力思考如何将 has_many(或在我的情况下为 has_one)与复合外键关联。

对于我的例子假设:

想象一下,我正在管理卖家和买家之间的关系,他们之间有一个初始合同,然后是任何数量的发票。所以模型看起来像这样:

class Invoice
  belongs_to :seller
  belongs_to :buyer
end
class Seller
  has_many :contracts
  has_many :invoices
end
class Buyer
  has_many :contracts
  has_many :invoices
end
class Contract
  belongs_to :seller
  belongs_to :buyer
end

每张发票都有一份初始合同(由卖方和买方定义)。我知道有各种各样的解决方案来构建实现这一目标的查询。理想情况下,虽然我想预先加载/加入发票列表的合同以避免 N+1 问题:

class Invoice
  belongs_to :seller
  belongs_to :buyer

  has_one :contract # options go here
end

编辑:架构就是这样。不幸的是,需要更改架构的解决方案不是一种选择。

解决方法

只需让发票属于合同,并从中获得买方和卖方。

class Invoice
  belongs_to :contract
end

然后通过联系人获取发票...

class Buyer
  has_many :contracts
  has_many :invoices,through: :contracts
end

class Seller
  has_many :contracts
  has_many :invoices,through: :contracts
end