2011-05-30 21 views
0

我有兩個型號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 

我已經debuggin這一點,我發現,當invoice.update_state運行self.payments是空的。看起來HABTM尚未更新。

我怎麼能解決這個問題?

+0

如何創建或更新付款和發票? invoices_are_of_this_account,:after_add =>:update_invoice_state,:after_remove =>:update_invoice_state 由於某種原因在這種情況下,關聯我用Payment.create(...,更新 – 2011-05-30 22:29:39

+0

我用它 驗證解決發票=> [..],...) – dwaynemac 2011-05-30 23:22:49

+0

: – dwaynemac 2011-05-30 23:23:33

回答

2

我相信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 

這應該可以解決您的問題。