Created
September 16, 2021 18:00
-
-
Save muyiwaoyeniyi/2105aa84962271098b16caabd7e634c4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # TIME ALLOWED: 15mins | |
| class User < ApplicationRecord | |
| has_many :customers | |
| end | |
| class Customer < ApplicationRecord | |
| belongs_to :user | |
| has_many :transactions | |
| end | |
| class Transaction < ApplicationRecord | |
| belongs_to :customer | |
| end | |
| class TransactionsController < ApplicationController | |
| def index | |
| user = User.find_by(id: params[:user_id]) | |
| raise unless user | |
| customers = Customer.where(user_id: user.id) | |
| customers.each { |customer| customer[:transactions] = customer.transactions } | |
| render json: customers | |
| end | |
| def transfer | |
| user = User.find_by(id: params[:user_id]) | |
| customer = Customer.find(params[:customer_id]) | |
| raise unless user&.id == customer&.user_id | |
| receiver = Customer.find(params[:receiver_id]) | |
| customer.update!(balance: customer.balance - params[:amount]) | |
| receiver.update!(balance: receiver.balance + params[:amount]) | |
| transaction = Transaction.create!(customer_id: customer.id, receiver_id: receiver.id, amount: params[:amount]) | |
| render json: transaction | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment