diff --git a/lib/active_record_bulk_insert.rb b/lib/active_record_bulk_insert.rb index 7a022a0..939743d 100644 --- a/lib/active_record_bulk_insert.rb +++ b/lib/active_record_bulk_insert.rb @@ -15,7 +15,7 @@ def self.bulk_insert(attrs, options = {}) return [] if attrs.empty? use_provided_primary_key = options.fetch(:use_provided_primary_key, false) - attributes = _resolve_record(attrs.first, options).keys.join(", ") + attributes = _resolve_record(attrs.first, options).keys invalid = [] if options.fetch(:validate, false) || options.fetch(:validate_with, false) @@ -24,15 +24,16 @@ def self.bulk_insert(attrs, options = {}) end values_sql = attrs.map do |record| - quoted = _resolve_record(record, options).map {|k, v| - _bulk_insert_quote(k, v) + resolved_record = _resolve_record(record, options) + quoted = attributes.map {|k| + _bulk_insert_quote(k, resolved_record.fetch(k)) } "(#{quoted.join(', ')})" end.join(",") sql = <<-SQL INSERT INTO #{quoted_table_name} - (#{attributes}) + (#{attributes.join(", ")}) VALUES #{values_sql} SQL diff --git a/spec/sample_record_spec.rb b/spec/sample_record_spec.rb index 1972efe..d1e7618 100644 --- a/spec/sample_record_spec.rb +++ b/spec/sample_record_spec.rb @@ -52,6 +52,15 @@ end.to_not raise_error end + it "handles multiple records with keys in different orders" do + SampleRecord.bulk_insert([{:name => "Foo", :age => 30}, {:age => 30, :name => "Foo"}]) + + SampleRecord.all.each do |record| + expect(record.name).to eq("Foo") + expect(record.age).to eq(30) + end + end + if ActiveRecord::VERSION::MAJOR >= 4 context "use_provided_primary_key" do it "relies on the DB to provide primary_key if :use_provided_primary_key is false or nil" do