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 class Client < ActiveRecord::Base
before_create :generate_key before_create :generate_key
validates :name, presence: true, uniqueness: true
validates :key, presence: true, uniqueness: true
def transactions def transactions
Transaction.where(origin: name) Transaction.where(origin: name)
end end

View file

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

View file

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