开发者

Rails 3 - Update Parent Class

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:

  1. 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?
  2. 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?
  3. 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜