我目前有一个has_many销售的ProductSale模型。同样,销售也属于发票。
我的目标是通过ProductSale与sales的关联访问发票。(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
发布于 2021-07-15 20:46:29
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方法来获取ProductSale对象的发票上的所有销售额。
发布于 2021-07-15 20:43:31
这样如何:
class ProductSale < ApplicationRecord
has_many :sales
has_one :sale
has_one :invoice, through: :sale
endhttps://stackoverflow.com/questions/68391528
复制相似问题