I would like to transact multiple model updates as a lump.
Let's say two models work when you do things like account transfer processing.
AccountTransaction models include
Payment side account id(withdrawal_account_id)
Receiver's account id(deposit_account_id)
Amount Transaction (amount)
has been newly recorded (saved) and
In the BasicIncomeAccount model,
The balance between the payer and the payer side is increased or decreased and updated.
Completely successful only commit to the two models.
So I tried writing the following code, but the model update failed.
Save to AccountTransaction is fine, but
It seems that the update to BasicIncomeAccount is not going well.
class AccountTransactionsController<ApplicationController
def create
begin
ActiveRecord::Base.transaction {
@account_transaction=AccountTransaction.new(
withdrawal_account_id —current_user.basic_income_account.id,
deposit_account_id:BasicIncomeAccount.find_by(account_number:params[:account_transaction][:deposit_account_id]).id,
amount:params [:account_transaction] [:amount]
)
@account_transaction.save!
# The following code is for recording in your BasicIncomeAccount
@withdrawal_basic_income_account=current_user.basic_income_account
@deposit_basic_come_account=BasicIncomeAccount.find_by(account_number:params[:account_transaction][:deposit_account_id])
@amount=params[:account_transaction][:amount].to_f
# Attempts to update both accounts traded on the following two lines failed
@withdrawal_basic_income_account.update(balance: @withdrawal_basic_income_account.balance-@amount)
@deposit_basic_income_account.update(balance:@deposit_basic_income_account.balance+@amount)
}
redirect_to root_path
rescue#Exception=>e
flash[:notice] = "Failed.Try again."
render "new"
end
I would appreciate it if you could let me know how I can completely successfully update the two models.
ruby-on-rails ruby
In conclusion, the problem was caused by an improper and unnecessary custom validation in the BasicIncomeAccount model.
Once you have removed any incorrect and unnecessary validation statements,
The code described in account_transactions_controller.rb above will work.
© 2024 OneMinuteCode. All rights reserved.