Skip to content

Instantly share code, notes, and snippets.

@mmclead
Created June 20, 2012 20:53
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 mmclead/2962150 to your computer and use it in GitHub Desktop.
Save mmclead/2962150 to your computer and use it in GitHub Desktop.
Create lots of records faster with raw SQL in RoR and PostgreSQL
#### Mass SQL INSERT Method ####
hash = {{a=>1,b=>2},{a=>3,b=>4},{a=>5,b=>6}} #data to insert
connection = ActiveRecord::Base.connection
if connection.adapter_name.downcase == "sqlite" #Default way to do things
parent.transaction do
hash.each do |h|
parent.children.create!(h)
end
end
elsif connection.adapter_name.downcase == "postgresql" #Faster way to do things
last_id = Child.last.id
columns = inserts = []
columns = hash.first.keys
columns.concat(["parent_id","id"])
hash.each {|c| inserts.push("(#{c.values.concat([parent.id,last_id+=1]).join(", ")})") }
sql = "INSERT INTO positions (#{columns.join(", ")}) VALUES #{inserts.join(", ")}".chomp
connection.execute sql
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment