-
Notifications
You must be signed in to change notification settings - Fork 9
/
stash.rb
33 lines (26 loc) · 1006 Bytes
/
stash.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# frozen_string_literal: true
# Stashes can be used to set money aside within an account
class Stash < ApplicationRecord
belongs_to :account
has_many :stash_entries, dependent: :delete_all
validates :name, presence: true,
length: { maximum: 50, minimum: 2 },
uniqueness: { scope: :account_id }
validates :goal, presence: true,
numericality: { greater_than_or_equal_to: :balance }
validates :balance, numericality: { greater_than_or_equal_to: 0 }
before_destroy :unstash
private
# Create an account transaction to return any stashed money
# to the Account balance when a Stash is deleted
def unstash
transaction = Transaction.new
transaction.trx_type = 'credit'
transaction.trx_date = Time.current
transaction.account_id = account_id
transaction.description = 'Transfer from ' + name + ' (Stash Deleted)'
transaction.amount = balance.abs
transaction.locked = true
transaction.save
end
end