has_and_belongs_to_many and after_save problem
I've got two models
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 - pa开发者_Python百科id_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
I've been debuggin this and I've found that when invoice.update_state is run self.payments is empty. Looks like HABTM hasn't been updated yet.
How could i solve this?
I believe HABTM has been mostly replaced by has_many :through.
You would create a join model, something like "InvoicePayment" (or something else creative)
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
This should fix your problem.
精彩评论