问题描述
||
我有两个模型
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
这应该可以解决您的问题。