多列外键 Ruby on Rails

问题描述 投票:0回答:1

我有以下型号:

公司、订单、发票

公司有很多订单,也有很多发票。订单有一张发票,属于一家公司。发票属于订单和公司。因此,订单引用 company_id,发票引用 company_id。我想确保发票 company_id 与其父订单的 company_id 相同。

注意:Postgres 支持这个。如何使用rails来实现? https://www.postgresql.org/docs/9.3/ddl-constraints.html#DDL-CONSTRAINTS-FK

  1. 我会创建一个外键来确保 Invoice order_id + company_id 作为 id + company_id 存在于订单中吗?
  2. 实现这一目标的最佳方法是什么?
  3. 这可以使用迁移来完成吗?
ruby-on-rails postgresql rails-migrations
1个回答
0
投票

亚格尼

你真的想得太多了,也太复杂了。您可以做的是摆脱由

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

这完全避免了整个问题。

© www.soinside.com 2019 - 2024. All rights reserved.