简体   繁体   English

通过 has_many 关系创建 has_one

[英]Creating a has_one through a has_many relationship

I currently have a ProductSale model that has_many sales.我目前有一个ProductSale模型,它有_many 销售额。 Also a sale belongs to an invoice.销售也属于发票。

My goal is to access an invoice through a ProductSale 's association to sales.我的目标是通过ProductSale与销售的关联访问发票。 (product_sale.invoice) (product_sale.invoice)

Current ProductSale model below:当前ProductSale模型如下:

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

However my current error is saying that this can't be done because the :through association is a collection , which i understand.但是我目前的错误是说这不能完成,因为:through association is a collection ,我理解。 Is there a way that this can be possible?有没有办法做到这一点?

 class Sale < ApplicationRecord belongs_to :invoice end

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

How about:怎么样:

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

All the sales on the ProductSale object have the same invoice. ProductSale对象上的所有销售额都具有相同的发票。 You know that you can just use the invoice of the first sale, but associations won't know that all the sales have the same invoice so you can use any, for instance the first one.您知道您可以只使用第一笔销售的发票,但协会不会知道所有销售都有相同的发票,因此您可以使用任何发票,例如第一个。

To have a invoices method to get each of the invoices you could do this:要使用invoices方法来获取每张发票,您可以执行以下操作:

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

However, if you want to use your business logic that all the invoices are assumed to be the same, you will have to write a method to implement that business logic.但是,如果您想使用假定所有发票都相同的业务逻辑,则必须编写一个方法来实现该业务逻辑。

class ProductSale < ApplicationRecord
    has_many :sales

    def invoice
      sales.first&.invoice
    end
end

If all the sales on the invoice will be sales in the ProductSale object, then maybe you should refactor as below.如果发票上的所有销售额都是ProductSale对象中的销售额,那么也许您应该重构如下。

class ProductSale < ApplicationRecord
    has_one :invoice
    delegate :sales, :to => :invoice, :prefix => false, :allow_nil => true
end

Then you can both call the invoice method to get the invoice and also call the sales method to get all the sales on the invoice for the ProductSale object.然后,您既可以调用invoice方法获取发票,也可以调用sales方法获取ProductSale对象发票上的所有销售额。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM