Created
June 20, 2012 20:53
-
-
Save mmclead/2962150 to your computer and use it in GitHub Desktop.
Create lots of records faster with raw SQL in RoR and PostgreSQL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#### 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