Skip to content

Commit

Permalink
Fix import of saved json[b] fields for postgres
Browse files Browse the repository at this point in the history
  • Loading branch information
stokarenko committed Feb 17, 2019
1 parent 562d2f9 commit 81b3f28
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/activerecord-import/import.rb
Original file line number Diff line number Diff line change
Expand Up @@ -577,7 +577,10 @@ def import_helper( *args )
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 }
attrs = column_names.select { |c|
attribute_type = type_for_attribute(c.to_s)
attribute_type.class == ActiveRecord::Type::Serialized || %i[json jsonb].include?(attribute_type.type)
}
Hash[attrs.map { |a| [a, nil] }]
else
serialized_attributes
Expand Down
2 changes: 2 additions & 0 deletions test/schema/postgresql_schema.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
t.text :preferences

if t.respond_to?(:json)
t.json :pure_json_data
t.json :data
else
t.text :data
Expand All @@ -20,6 +21,7 @@
end

if t.respond_to?(:jsonb)
t.jsonb :pure_jsonb_data
t.jsonb :settings
t.jsonb :json_data, null: false, default: {}
else
Expand Down
13 changes: 13 additions & 0 deletions test/support/postgresql/import_examples.rb
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,19 @@ def should_support_postgresql_import_functionality
assert_equal({}, Vendor.first.json_data)
end
end

%w[json jsonb].each do |json_type|
describe "with pure #{json_type} fields" do
let(:data) { {a: :b} }
let(:json_field_name) { "pure_#{json_type}_data" }
it "imports the values from saved records" do
vendor = Vendor.create!(name: 'Vendor 1', json_field_name => data)

Vendor.import [vendor], on_duplicate_key_update: [json_field_name]
assert_equal(data.as_json, vendor.reload[json_field_name])
end
end
end
end

describe "with binary field" do
Expand Down

0 comments on commit 81b3f28

Please sign in to comment.