Skip to content

Instantly share code, notes, and snippets.

@telagraphic
Last active December 11, 2015 05:18
Show Gist options
  • Save telagraphic/4551101 to your computer and use it in GitHub Desktop.
Save telagraphic/4551101 to your computer and use it in GitHub Desktop.
module AccountBalances
def credit_to_balance(account, credit)
if account.update_attributes(balance: account.balance + credit.amount)
account
else
false
end
end
def debit_from_balance(account, debit)
if account.balance < debit.amount
#flash[:notice] = "debit.amount > account.balance"
false
else
account.update_attributes(balance: account.balance -= debit.amount)
account
end
end
end
class DebitsController < ApplicationController
def new
@current_account = signed_in_user.accounts.find(params[:account_id])
@new_debit = @current_account.debits.build(params[:debit])
end
def create
@current_account = signed_in_user.accounts.find(params[:account_id])
@new_debit = @current_account.debits.build(params[:debit])
@new_debit = @current_account.debits.debit_from_balance(@current_account, @new_debit)
if @new_debit.save
redirect_to account_path(@current_account)
else
render "new"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment