class PPaymentDocument < ActiveRecord::Base belongs_to :p_document belongs_to :p_payment validates :p_document_id, :presence => true #validates :p_payment_id, :presence => true validates :amount, :presence => true after_save do self.p_document.save end after_destroy do self.p_payment.save if self.p_payment end def siblings_payments siblings_payments = self.p_document.p_payment_documents.joins(:p_payment).where(:p_payments => {:canceled => false}) siblings_payments = siblings_payments.where("p_payment_documents.id != ?", self.id) if self.id return siblings_payments end def siblings_payments_total self.siblings_payments.sum(:amount) end before_validation do if self.p_document sum = self.siblings_payments_total.to_f + self.amount.to_f if sum.round(2) > self.p_document.totals[:total_ttc].to_f.round(2) errors.add(:amount, "Ne doit pas dépasser le montant de la somme restant dues (#{(self.p_document.totals[:total_ttc].to_f.round(2) - siblings_payments_total.to_f.round(2)).round(2)})") end end end end