Skip to content

Instantly share code, notes, and snippets.

@sprite2005
Created February 18, 2009 04:48
Show Gist options
  • Save sprite2005/66196 to your computer and use it in GitHub Desktop.
Save sprite2005/66196 to your computer and use it in GitHub Desktop.
def update_balance
received_query = "select sum(receiver_cents) as receiver_cents, receiver_currency from `transaction_items` where `transaction_receiver_account_id`='"+user.id.to_s+"' and `receiver_accounted`='1' group by `receiver_currency`;"
sent_query = "select sum(sender_cents) as sender_cents, sender_currency from `transaction_items` where `transaction_sender_account_id`='"+user.id.to_s+"' and `sender_accounted`='1' group by `sender_currency`;"
calculated_balance = Money.new(0, "USD")
# There are very few reasons you should ever need to do this...
# This could be considered one of them -_-
result = connection.execute(received_query);
result.each_hash do |t|
calculated_balance += Money.new(t['receiver_cents'].to_f,t['receiver_currency'])
end
result.free
result = connection.execute(sent_query);
result.each_hash do |t|
calculated_balance += Money.new(t['sender_cents'].to_f,t['sender_currency'])
end
result.free
self.balance = calculated_balance
save
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment