1

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?

1 Answer 1

1
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
Sign up to request clarification or add additional context in comments.

2 Comments

This works great -- thanks! (Should be "returning id", though)
I have been using a similar approach, but in Rails 4.1 ActiveRecord::Base.connection is deprecated and this throws an error when using RETURNING id in the SQL statement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.