Preserve user-field options when updating user-fields

Avoid deleting options of the user-field when no options are
transmitted.
This commit is contained in:
Jonathan Brachthaeuser 2015-08-17 19:01:15 +02:00
parent d87520a2cf
commit c0e88724c2
2 changed files with 23 additions and 4 deletions

View file

@ -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

View file

@ -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