Reputation: 13
I'm trying to import data from a csv file following the example given by Jonaphin at http://www.genesx.com/2012/06/import-csv-files-100x-faster-in-rails-3/
I'm trying to get the index of the last insert from postgres, but for some reason the code isn't working.
def process_data!(file, survey_id)
headers = [
"zip_code",
"booking_date"
]
ActiveRecord::Base.establish_connection
created_at = Time.now.strftime("%Y-%m-%d %H:%M:%S")
CSV.foreach(file, {headers: :first_row}) do |row|
sql_keys = []
sql_vals = []
headers.each_with_index do |key, idx|
val = row[idx]
sql_keys << key
sql_vals << ActiveRecord::Base.connection.quote(val)
end
sql = "
INSERT INTO bookings (survey_id, #{sql_keys.join(', ')}, created_at, updated_at)
VALUES (#{survey_id}, #{sql_vals.join(', ')}, '#{created_at}', '#{created_at}')
"
booking_id = ActiveRecord::Base.connection.insert(sql)
end
end
booking_id
should now have the id of the last inserted row, but for some reason it is nil
.
I tried running ActiveRecord::Base.connection.insert(sql)
in the console and it worked (i.e., it returned the id I wanted).
Anyone know what's going wrong here? Is there some setting I need to change to allow postgres to return the last id?
Upvotes: 1
Views: 1759
Reputation: 125244
INSERT INTO bookings (survey_id, #{sql_keys.join(', ')}, created_at, updated_at)
VALUES (#{survey_id}, #{sql_vals.join(', ')}, '#{created_at}', '#{created_at}')
returning survey_id
Upvotes: 1