has_and_belongs_to_many和after_save问题

时间:2011-05-30 22:07:32

标签: ruby-on-rails

我有两个型号

class Payment < ActiveRecord::Base
  has_and_belongs_to_many :invoices

  after_save :update_invoices_state

  def update_invoices_state
    self.invoices.each{|i| i.update_state }
  end
end

class Invoice < ActiveRecord::Base
  has_and_belongs_to_many :payments

  def pending_value
    paid_value = Money.new(0,self.currency)
    self.payments.each{|payment| paid_value += payment.value}
    self.value - paid_value
  end

  def update_state
    if self.pending_value.cents >= 0
      if self.due_on >= Time.zone.today
        new_state = :past_due_date
      else
        new_state = :pending
      end
    else
      new_state = :paid
    end
    self.update_attribute :state, new_state
  end
end

我已经调试了这个,我发现当invoice.update_state运行时,self.payments为空。看起来HABTM还没有更新。

我怎么能解决这个问题?

1 个答案:

答案 0 :(得分:2)

我认为HABTM大多被has_many取代:通过。

您可以创建一个连接模型,例如“InvoicePayment”(或其他创意)

class Payment < ActiveRecord::Base
    has_many :invoice_payments
    has_many :invoices, :through => :invoicepayments
end

class InvoicePayment < ActiveRecord::Base
    belongs_to :invoice
    belongs_to :payment
end

class Invoice < ActiveRecord::Base
    has_many :invoice_payments
    has_many :payments, :through => :invoice_payments 
end

这可以解决您的问题。