diff --git a/app/controllers/concerns/transactions_query.rb b/app/controllers/concerns/transactions_query.rb index 8fb5b86..bd87edc 100644 --- a/app/controllers/concerns/transactions_query.rb +++ b/app/controllers/concerns/transactions_query.rb @@ -12,7 +12,6 @@ class TransactionsQuery def query Arel::SelectManager.new(ActiveRecord::Base) .from(arel) - .order(@arel_table[:time].desc) end def arel diff --git a/app/controllers/transactions_controller.rb b/app/controllers/transactions_controller.rb index f4c1e54..f9d1be7 100644 --- a/app/controllers/transactions_controller.rb +++ b/app/controllers/transactions_controller.rb @@ -1,20 +1,20 @@ class TransactionsController < ApplicationController - load_and_authorize_resource skip_before_filter :verify_authenticity_token, only: :create before_action :authenticate_user!, except: :create before_action :authenticate_user_or_client!, only: :create respond_to :js, only: :create - def index - @transactions = Transaction.all - end - def create + @transaction = Transaction.new(transaction_params) + @transaction.reverse if @transaction.amount < 0 + authorize!(:create, @transaction) + if @transaction.save head :created else - render json: @transaction.errors.full_messages, status: :unprocessable_entity + render json: @transaction.errors.full_messages, + status: :unprocessable_entity end end diff --git a/app/models/transaction.rb b/app/models/transaction.rb index 3c7b8a5..34746ef 100644 --- a/app/models/transaction.rb +++ b/app/models/transaction.rb @@ -24,13 +24,6 @@ class Transaction < ActiveRecord::Base validates :amount, numericality: { greater_than: 0 } validate :different_debtor_creditor - def initialize *args, **kwargs - super *args, **kwargs - if amount < 0 - self.creditor, self.debtor = debtor, creditor - self.amount = self.amount.abs - end - end def peer_of(user) return creditor if user == debtor @@ -42,6 +35,11 @@ class Transaction < ActiveRecord::Base return amount if user == creditor end + def reverse + self.creditor, self.debtor = self.debtor, self.creditor + self.amount *= -1 + end + private def recalculate_balances diff --git a/spec/models/transaction_spec.rb b/spec/models/transaction_spec.rb index d05aaf8..67b15fc 100644 --- a/spec/models/transaction_spec.rb +++ b/spec/models/transaction_spec.rb @@ -35,5 +35,4 @@ RSpec.describe Transaction, type: :model do expect {trans.save!}.to change {@user.balance}.by(-10) end end - end