我有以下型号:
公司、订单、发票
公司有很多订单,也有很多发票。订单有一张发票,属于一家公司。发票属于订单和公司。因此,订单引用 company_id,发票引用 company_id。我想确保发票 company_id 与其父订单的 company_id 相同。
注意:Postgres 支持这个。如何使用rails来实现? https://www.postgresql.org/docs/9.3/ddl-constraints.html#DDL-CONSTRAINTS-FK
你真的想得太多了,也太复杂了。您可以做的是摆脱由
invoices.company_id
引起的不必要的重复,而只是设置一个间接关联:
class Company < ApplicationRecord
has_many :orders
has_many :invoices, through: :orders
end
class Order < ApplicationRecord
belongs_to :company
has_many :invoices
end
class Invoice < ApplicationRecord
belongs_to :order
# joins the company through the orders.company_id column
has_one :company,
through: :order
end
这完全避免了整个问题。