I have a Trans
(transaction) class in my application that submits a transaction to the server. When a transaction is submitted, I also want to do an update on a parent User class to update their cached "balance." Here is relevant code:
# tran.rb
class Tran < ActiveRecord::Base
belongs_to :submitting_user, :class_name => 'User'
end
And my control开发者_StackOverflow中文版ler:
#trans_controller.rb
def create
@title = "Create Transaction"
# Add the transaction from the client
@tran = Tran.new(params[:tran])
# Update the current user
@tran.submitting_user_id = current_user.id
# ERROR: This line is not persisted
@tran.submitting_user.current_balance = 4;
# Save the transaction
if @tran.save
flash[:success] = 'Transaction was successfully created.'
redirect_to trans_path
I have a couple of problems:
- When I update the current_balance field on the user, that balance isn't persisted on the user after the transaction is saved. I think maybe I need to use
update_attributes
? - I am not even sure that the code should be a part of my controller - maybe it makes more sense in the
before_save
of my model? - Will either of these make this transactional?
def create
title = "Create Transaction"
@tran = Tran.new(params[:tran])
@tran.submitting_user_id = current_user.id
# to make it "transactional" you should put it after @tran.save
if @tran.save
current_user.update_attribute :current_balance, 4
...
And yes - it is better to put it into after_save
callback
class Tran < AR::Base
after_save :update_user_balance
private
def update_user_balance
submitting_user.update_attribute :current_balance, 4
end
end
精彩评论