Skip to content

Commit

Permalink
ActiveRecord Enum fields could not be updated correctly. Fixes #2713, C…
Browse files Browse the repository at this point in the history
…loses #2659
  • Loading branch information
mshibuya committed Sep 19, 2016
1 parent ae17302 commit 33342c0
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 7 deletions.
15 changes: 9 additions & 6 deletions lib/rails_admin/config/fields/types/active_record_enum.rb
Original file line number Diff line number Diff line change
Expand Up @@ -28,24 +28,27 @@ 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)
params[name] = parse_value(params[name]) if params[name]
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
Expand Down
16 changes: 15 additions & 1 deletion spec/integration/config/edit/rails_admin_config_edit_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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

Expand Down

0 comments on commit 33342c0

Please sign in to comment.