Justin
Justin

Reputation: 1956

Rails 3 Updating an Associated Model

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?

Upvotes: 2

Views: 611

Answers (1)

Dylan Markow
Dylan Markow

Reputation: 124469

Since you're trying to update a different model (a Loan instead of a Transaction), you need to actually save your update manually. Also, you're calling Loan (the whole class) rather than loan (your transaction's loan). This should work:

def modify_loan
  newamount = loan.amount_remaining - self.amount
  loan.update_attributes(:amount_remaining => newamount)
end

Upvotes: 3

Related Questions