From 33342c0d1bdb9d4f74417984f414f9cc1e4d5b28 Mon Sep 17 00:00:00 2001 From: "M.Shibuya" Date: Mon, 19 Sep 2016 15:28:22 +0900 Subject: [PATCH] ActiveRecord Enum fields could not be updated correctly. Fixes #2713, Closes #2659 --- .../config/fields/types/active_record_enum.rb | 15 +++++++++------ .../config/edit/rails_admin_config_edit_spec.rb | 16 +++++++++++++++- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/lib/rails_admin/config/fields/types/active_record_enum.rb b/lib/rails_admin/config/fields/types/active_record_enum.rb index 5f14ac3375..e6aea3f4a0 100644 --- a/lib/rails_admin/config/fields/types/active_record_enum.rb +++ b/lib/rails_admin/config/fields/types/active_record_enum.rb @@ -28,7 +28,12 @@ def type end def parse_value(value) - value.present? ? enum.invert[type_cast_value(value)] : nil + return unless value.present? + if ::Rails.version >= '5' + abstract_model.model.attribute_types[name.to_s].deserialize(value) + else + enum.invert[type_cast_value(value)] + end end def parse_input(params) @@ -36,16 +41,14 @@ def parse_input(params) end def form_value - ::Rails.version >= '5' ? enum[super] : super + enum[super] || super end private def type_cast_value(value) - if ::Rails.version >= '5' - abstract_model.model.attribute_types[name].cast(value) - elsif ::Rails.version >= '4.2' - abstract_model.model.column_types[name].type_cast_from_user(value) + if ::Rails.version >= '4.2' + abstract_model.model.column_types[name.to_s].type_cast_from_user(value) else abstract_model.model.column_types[name.to_s].type_cast(value) end diff --git a/spec/integration/config/edit/rails_admin_config_edit_spec.rb b/spec/integration/config/edit/rails_admin_config_edit_spec.rb index 20665e2936..b033f1d2a7 100644 --- a/spec/integration/config/edit/rails_admin_config_edit_spec.rb +++ b/spec/integration/config/edit/rails_admin_config_edit_spec.rb @@ -1180,7 +1180,9 @@ class FieldTestWithEnum < FieldTest RailsAdmin.config.included_models = [FieldTestWithEnum] RailsAdmin.config FieldTestWithEnum do edit do - field :integer_field + field :integer_field do + default_value 'foo' + end end end end @@ -1200,6 +1202,18 @@ class FieldTestWithEnum < FieldTest visit edit_path(model_name: 'field_test_with_enum', id: FieldTestWithEnum.create(integer_field: 'bar')) expect(find('.enum_type select').value).to eq '1' end + + it 'can be updated' do + visit edit_path(model_name: 'field_test_with_enum', id: FieldTestWithEnum.create(integer_field: 'bar')) + select 'foo' + click_button 'Save' + expect(FieldTestWithEnum.first.integer_field).to eq 'foo' + end + + it 'pre-populates default value' do + visit new_path(model_name: 'field_test_with_enum') + expect(find('.enum_type select').value).to eq '0' + end end end