0

Hello I have 2 models here:

class Account < ActiveRecord::Base
  belongs_to :user
  has_many :transactions
end

class Transaction < ActiveRecord::Base
  belongs_to :account
  after_create :update_balance

  def update_balance
   balance = self.account.balance
   self.account.update(balance: balance - self.price)
  end
end

1) Currently, I have an account with balance, and able to update the balance everytime I have created a transaction. But in the future, I will have a updated transaction, where it could get a new price, which I store in another field call new_price, and once we update the new price, how can we add to the account balance?

2) We are going to chart an account balance movement, so we need to store every account balance history, is it a good way if we create a new account field, for everytime we got a new transaction?

Thanks.

pyfl88
  • 1,680
  • 16
  • 26

1 Answers1

0

There should be a bit more complex logic. About your questions:

1) You shouldn't update payment transaction because you would get a side affects (like not valid balance on some accounts, transaction history, etc.). The better way is a rollback your transaction. There you would pass validation logic (e.g. cannot rollback if future balance of asset account will be negative, etc.)

2) For storing payment history you should use your Transaction model.

Also there a lot of another interesting moments. If you want you can see my gem for this job. You can install it (if you use Rails) or use some business logic for your payment system.

Alexander Shlenchack
  • 3,779
  • 6
  • 32
  • 46