Add validations

This commit is contained in:
benji 2015-09-08 15:51:23 +02:00
parent cbb3284622
commit 599570f033
3 changed files with 14 additions and 0 deletions

View file

@ -12,6 +12,9 @@
class Client < ActiveRecord::Base
before_create :generate_key
validates :name, presence: true, uniqueness: true
validates :key, presence: true, uniqueness: true
def transactions
Transaction.where(origin: name)
end

View file

@ -19,13 +19,21 @@ class Transaction < ActiveRecord::Base
after_save :recalculate_balances
after_destroy :recalculate_balances
validates :amount, numericality: { greater_than: 0 }
validate :different_debtor_creditor
def client
Client.find_by name: origin
end
private
def recalculate_balances
creditor.calculate_balance!
debtor.calculate_balance!
end
def different_debtor_creditor
self.errors.add :base, "Can't write money to yourself" if self.debtor == self.creditor
end
end

View file

@ -17,6 +17,9 @@ class User < ActiveRecord::Base
has_many :outgoing_transactions,
class_name: 'Transaction', foreign_key: 'debtor_id'
validates :name, presence: true, uniqueness: true
validates :balance, presence: true
def transactions
Transaction.where("creditor_id = ? OR debtor_id = ?", id, id)
end