【问题标题】:Creating a has_one through a has_many relationship通过 has_many 关系创建 has_one
【发布时间】: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


【解决方案1】:

怎么样:

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

【讨论】:

    【解决方案2】:

    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 对象的发票上的所有销售额。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-12
      • 2015-09-21
      相关资源
      最近更新 更多