diff --git a/app/controllers/admin/user_fields_controller.rb b/app/controllers/admin/user_fields_controller.rb index 0980381ec44..fceecfa7d18 100644 --- a/app/controllers/admin/user_fields_controller.rb +++ b/app/controllers/admin/user_fields_controller.rb @@ -9,7 +9,7 @@ class Admin::UserFieldsController < Admin::AdminController field.position = (UserField.maximum(:position) || 0) + 1 field.required = params[:required] == "true" - fetch_options(field) + update_options(field) json_result(field, serializer: UserFieldSerializer) do field.save @@ -30,8 +30,7 @@ class Admin::UserFieldsController < Admin::AdminController field.send("#{col}=", field_params[col]) end end - UserFieldOption.where(user_field_id: field.id).delete_all - fetch_options(field) + update_options(field) if field.save render_serialized(field, UserFieldSerializer, root: 'user_field') @@ -48,9 +47,10 @@ class Admin::UserFieldsController < Admin::AdminController protected - def fetch_options(field) + def update_options(field) options = params[:user_field][:options] if options.present? + UserFieldOption.where(user_field_id: field.id).delete_all field.user_field_options_attributes = options.map {|o| {value: o} }.uniq end end diff --git a/spec/controllers/admin/user_fields_controller_spec.rb b/spec/controllers/admin/user_fields_controller_spec.rb index bd6bd517dba..fe63ce860de 100644 --- a/spec/controllers/admin/user_fields_controller_spec.rb +++ b/spec/controllers/admin/user_fields_controller_spec.rb @@ -74,6 +74,25 @@ describe Admin::UserFieldsController do expect(user_field.field_type).to eq('dropdown') expect(user_field.user_field_options.size).to eq(2) end + + it "keeps options when updating the user field" do + xhr :put, :update, id: user_field.id, user_field: {name: 'fraggle', + field_type: 'dropdown', + description: 'muppet', + options: ['hello', 'hello', 'world'], + position: 1} + expect(response).to be_success + user_field.reload + expect(user_field.user_field_options.size).to eq(2) + + xhr :put, :update, id: user_field.id, user_field: {name: 'fraggle', + field_type: 'dropdown', + description: 'muppet', + position: 2} + expect(response).to be_success + user_field.reload + expect(user_field.user_field_options.size).to eq(2) + end end end