From 38e75de5cbc59949dfd6de0b6f10c82e90d7af2d Mon Sep 17 00:00:00 2001 From: dgpangan Date: Mon, 20 Feb 2023 07:21:41 +0800 Subject: [PATCH] ref: reservations controller --- app/controllers/reservations_controller.rb | 33 ++++++++++++++++++---- 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/app/controllers/reservations_controller.rb b/app/controllers/reservations_controller.rb index 3e30f8c..46ccdb3 100644 --- a/app/controllers/reservations_controller.rb +++ b/app/controllers/reservations_controller.rb @@ -5,12 +5,22 @@ class ReservationsController < ApplicationController def create data = parse_data(JSON.parse(request.raw_post).smash) - Guest.upsert(data[:guest]) - guest = Guest.find_by(email: data[:guest][:email]) - data[:reservation][:guest_id] = guest.id - Reservation.upsert(data[:reservation]) - reservation = Reservation.find_by(code: data[:reservation][:code]) - render json: { guest:, reservation: } + + guest = create_or_update_guest(data[:guest]) + + unless guest.valid? + render json: { success: false, errors: guest.errors } + return + end + + reservation = create_or_update_reservation(data[:reservation], guest.id) + + unless reservation.valid? + render json: { success: false, errors: reservation.errors } + return + end + + render json: { success: true, guest:, reservation: } end private @@ -30,4 +40,15 @@ def parse_data(data) reservation[:guest_id] = guest[:id] { reservation:, guest: } end + + def create_or_update_guest(data) + Guest.upsert(data) + Guest.find_by(email: data[:email]) + end + + def create_or_update_reservation(data, guest_id) + data[:guest_id] = guest_id + Reservation.upsert(data) + Reservation.find_by(code: data[:code]) + end end