Skip to content
Open
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
9 changes: 5 additions & 4 deletions lib/active_record_bulk_insert.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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
Expand Down
9 changes: 9 additions & 0 deletions spec/sample_record_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down