From b91539d68fa21979001e122c912fad1c31dfd5d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Matija=20=C4=8Cupi=C4=87?= Date: Sat, 13 Jan 2018 02:10:04 +0100 Subject: Refactor VariablesController#save_multiple --- app/controllers/projects/variables_controller.rb | 22 +++++++++++++--------- 1 file changed, 13 insertions(+), 9 deletions(-) (limited to 'app/controllers/projects/variables_controller.rb') diff --git a/app/controllers/projects/variables_controller.rb b/app/controllers/projects/variables_controller.rb index f9d548a14f8..9aacb53078a 100644 --- a/app/controllers/projects/variables_controller.rb +++ b/app/controllers/projects/variables_controller.rb @@ -35,17 +35,12 @@ class Projects::VariablesController < Projects::ApplicationController def save_multiple respond_to do |format| format.json do - variables = [] - variables_params[:variables].each do |variable_hash| - variable = project.variables.where(key: variable_hash[:key]).first_or_initialize(variable_hash) - variable.assign_attributes(variable_hash) unless variable.new_record? - return head :bad_request unless variable.valid? + variables = variables_from_params(variables_params) + return head :bad_request unless variables.all?(&:valid?) - variables << variable - end - variables.each { |variable| variable.save } + variables.each(&:save) + head :ok end - head :ok end end @@ -71,6 +66,15 @@ class Projects::VariablesController < Projects::ApplicationController params.permit(variables: [*variable_params_attributes]) end + def variables_from_params(params) + params[:variables].map do |variable_hash| + variable = project.variables.where(key: variable_hash[:key]) + .first_or_initialize(variable_hash) + variable.assign_attributes(variable_hash) unless variable.new_record? + variable + end + end + def variable_params_attributes %i[id key value protected _destroy] end -- cgit v1.2.1