Skip to content

Commit

Permalink
Fix issue importing serialized attributes from saved models
Browse files Browse the repository at this point in the history
  • Loading branch information
jkowens committed Jun 6, 2017
1 parent bb8c255 commit 2a6158d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 2 deletions.
11 changes: 9 additions & 2 deletions lib/activerecord-import/import.rb
Original file line number Diff line number Diff line change
Expand Up @@ -435,13 +435,20 @@ def import_helper( *args )
column_names.delete(primary_key)
end

stored_attrs = respond_to?(:stored_attributes) ? stored_attributes : {}
default_values = column_defaults
stored_attrs = respond_to?(:stored_attributes) ? stored_attributes : {}
serialized_attrs = if defined?(ActiveRecord::Type::Serialized)
attrs = column_names.select { |c| type_for_attribute(c.to_s).class == ActiveRecord::Type::Serialized }
Hash[attrs.map { |c| [c, nil] }]
else
serialized_attributes
end

array_of_attributes = models.map do |model|
column_names.map do |name|
is_stored_attr = stored_attrs.any? && stored_attrs.key?(name.to_sym)
if is_stored_attr || default_values[name].is_a?(Hash)
is_serialized_attr = serialized_attrs.any? && serialized_attrs.key?(name)
if is_stored_attr || is_serialized_attr || default_values[name].is_a?(Hash)
model.read_attribute(name.to_s)
else
model.read_attribute_before_type_cast(name.to_s)
Expand Down
10 changes: 10 additions & 0 deletions test/import_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -692,6 +692,16 @@
assert_equal(data.as_json, Widget.find_by_w_id(9).json_data)
end

it "imports serialized values from saved records" do
Widget.import [:w_id, :json_data], [[1, data]]
assert_equal data.as_json, Widget.last.json_data

w = Widget.last
w.w_id = 2
Widget.import([w])
assert_equal data.as_json, Widget.last.json_data
end

context "with a store" do
it "imports serialized attributes set using accessors" do
vendors = [Vendor.new(name: 'Vendor 1', color: 'blue')]
Expand Down

0 comments on commit 2a6158d

Please sign in to comment.