I have a Rails 3 application with Loan and Transaction objects. When a Transaction is saved, I want to deduct the Transaction.amount from the Loan.amount_remaining in an after_save model method, modify_loan, in the Transaction model.
Is this the best place for this code (as opposed to calling an update method in the Loan model), and if so, how do I access and save Loan data from the Transaction model?
Here’s what I’ve been trying to do:
class Transaction < ActiveRecord::Base
belongs_to :loan
belongs_to :customer
after_save :modify_loan
def modify_loan
newamount = Loan.amount_remaining - self.amount
if amount >= 0
Loan.amount_remaining = newamount
else
nil
end
end
end
However, this obviously isn’t working. Does anyone know the proper way to do this? I feel like I’ve found some related questions on SO using Model.build, but how is this used?
Since you’re trying to update a different model (a
Loaninstead of aTransaction), you need to actually save your update manually. Also, you’re callingLoan(the whole class) rather thanloan(your transaction’s loan). This should work: