diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index 7834c60..e4ae47d 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -5,6 +5,10 @@ class ApplicationController < ActionController::API before_action :configure_permitted_parameters, if: :devise_controller? + rescue_from ActionController::ParameterMissing do |e| + render json: { error: e.message }, status: :bad_request + end + protected def configure_permitted_parameters diff --git a/app/controllers/tournaments_controller.rb b/app/controllers/tournaments_controller.rb index 94e98c0..55143ab 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] + before_action :validate_create_params, only: %i[create] rescue_from ActiveRecord::RecordNotFound, with: :render_not_found_error # GET /tournaments @@ -71,4 +72,11 @@ class TournamentsController < ApplicationController def tournament_params params.slice(:name, :description, :public, :teams).permit! end + + def validate_create_params + teams = params['teams'] + return if teams.is_a?(Array) && teams.reject { |t| t.is_a? ActionController::Parameters }.count.zero? + + render json: { error: 'Invalid teams array' }, status: :unprocessable_entity + end end diff --git a/spec/controllers/tournaments_controller_spec.rb b/spec/controllers/tournaments_controller_spec.rb index 772a5b3..88d6a6b 100644 --- a/spec/controllers/tournaments_controller_spec.rb +++ b/spec/controllers/tournaments_controller_spec.rb @@ -142,6 +142,13 @@ RSpec.describe TournamentsController, type: :controller do end.to change(Team, :count).by(data[:teams].count) end end + + context 'with invalid parameters' do + it 'renders an unprocessable entity response' do + put :create, params: { teams: [1, 2, 3] } + expect(response).to have_http_status(:unprocessable_entity) + end + end end end