has_and_belongs_to_many和after_save问题

问题描述

|| 我有两个模型
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尚未更新。 我该如何解决?     

解决方法

        我相信HABTM已被has_many:through取代。 您将创建一个联接模型,例如\“ 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
这应该可以解决您的问题。     

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...