Skip to content

Instantly share code, notes, and snippets.

@thermistor
Forked from maxjustus/bulk_insert.rb
Created March 14, 2018 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thermistor/161702f47ae70bdc4adb198afb3cdd88 to your computer and use it in GitHub Desktop.
Save thermistor/161702f47ae70bdc4adb198afb3cdd88 to your computer and use it in GitHub Desktop.
Simple SQL bulk insert in Rails
# Takes a table name, and an array of hashes where keys are column names and values are values.
# Expects hashes to all contain the same keys.
def bulk_insert(table, rows)
columns = rows.first.keys
to_insert = rows.map do |d|
vals = columns.map {|k| d[k] }
ActiveRecord::Base.send(:replace_bind_variables, "(#{vals.length.times.collect {'?'}.join(',')})", vals)
end
ActiveRecord::Base.connection.execute(<<-SQL)
INSERT INTO
#{table}
(#{columns.join(',')})
VALUES #{to_insert.join(",")}
SQL
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment