【发布时间】:2021-09-24 05:26:41
【问题描述】:
我目前有一个 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
【问题讨论】:
-
Rails 如何知道要进行哪个销售才能获得发票?它不能。这需要是一个模型方法,您可以在其中放置正确的逻辑。
-
是的,我知道你的意思。就我而言,每笔销售都将具有相同的 invoice_id,所以我认为 rails 可以从那里解决。不过谢谢你的回答。
标签: ruby-on-rails model associations