通过 has_many 关系创建 has_one

时间:2021-07-15 09:46:44

标签: ruby-on-rails model associations

我目前有一个 ProductSale 模型,有_many 销售额。 销售也属于发票。

我的目标是通过 ProductSale 与销售的关联访问发票。 (product_sale.invoice)

当前的 ProductSale 模型如下:

class ProductSale < ApplicationRecord
    has_many :sales
    has_one :invoice, through: :sales
end

然而,我目前的错误是无法做到这一点,因为 :through association is a collection,我理解。有没有办法做到这一点?

class Sale < ApplicationRecord
  belongs_to :invoice
 end

class Invoice < ApplicationRecord
  has_many :sales, inverse_of: :invoice, dependent: :destroy
end

2 个答案:

答案 0 :(得分:0)

怎么样:

class ProductSale < ApplicationRecord
  has_many :sales
  has_one :sale
  has_one :invoice, through: :sale
end

答案 1 :(得分:0)

$ k3s kubectl get svc NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE nginx LoadBalancer 10.43.169.6 10.186.0.17,10.186.0.18 8080:31762/TCP 50m nginx-two LoadBalancer 10.43.118.82 10.186.0.17,10.186.0.18 8090:31780/TCP 4m44s 对象上的所有销售额都具有相同的发票。您知道您可以只使用第一笔销售的发票,但协会不会知道所有销售都有相同的发票,因此您可以使用任何发票,例如第一个。

要使用 ProductSale 方法获取每张发票,您可以这样做:

invoices

但是,如果您想使用假设所有发票都相同的业务逻辑,则必须编写一个方法来实现该业务逻辑。

class ProductSale < ApplicationRecord
    has_many :sales
    has_many :invoices, through: :sales
end

如果发票上的所有销售额都是 class ProductSale < ApplicationRecord has_many :sales def invoice sales.first&.invoice end end 对象中的销售额,那么也许您应该进行如下重构。

ProductSale

然后,您既可以调用 class ProductSale < ApplicationRecord has_one :invoice delegate :sales, :to => :invoice, :prefix => false, :allow_nil => true end 方法获取发票,也可以调用 invoice 方法获取 sales 对象的发票上的所有销售额。