Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix import of saved json[b] fields for postgres #594

Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 do |c|
attribute_type = type_for_attribute(c.to_s)
attribute_type.class == ActiveRecord::Type::Serialized || %i(json jsonb).include?(attribute_type.type)
end
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