From a2e35e171041dd3a4dbafe431e07fbc29d4c2ab7 Mon Sep 17 00:00:00 2001 From: Thor77 Date: Mon, 8 Apr 2019 11:16:01 +0200 Subject: [PATCH] Create teams with only name attribute --- app/controllers/application_controller.rb | 4 ++++ app/controllers/tournaments_controller.rb | 16 ++++++++++++++-- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 803d135..7834c60 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -24,4 +24,8 @@ class ApplicationController < ActionController::API ] }, status: :forbidden end + + def render_not_found_error(exception) + render json: { error: exception.to_s }, status: :not_found + end end diff --git a/app/controllers/tournaments_controller.rb b/app/controllers/tournaments_controller.rb index c800b07..94e98c0 100644 --- a/app/controllers/tournaments_controller.rb +++ b/app/controllers/tournaments_controller.rb @@ -4,6 +4,7 @@ class TournamentsController < ApplicationController before_action :set_tournament, only: %i[show update destroy] before_action :authenticate_user!, only: %i[create update destroy] before_action -> { require_owner! @tournament.owner }, only: %i[update destroy] + rescue_from ActiveRecord::RecordNotFound, with: :render_not_found_error # GET /tournaments def index @@ -19,9 +20,20 @@ class TournamentsController < ApplicationController # POST /tournaments def create params = tournament_params - teams = params.delete 'teams' + params.require(:teams) + # convert teams parameter into Team objects + teams = params.delete('teams').map do |team| + if team[:id] + Team.find team[:id] + elsif team[:name] + Team.create name: team[:name] + end + end + # create tournament tournament = current_user.tournaments.new params - tournament.teams = Team.find(teams.map { |t| t[:id] }) + # associate provided teams with tournament + tournament.teams = teams + # validate tournament unless tournament.valid? render json: tournament.errors, status: :unprocessable_entity return