我正在尝试按照Jonaphin在http://www.genesx.com/2012/06/import-csv-files-100x-faster-in-rails-3/提供的示例从csv文件导入数据
我正在尝试从postgres获取最后一个插入的索引,但由于某种原因,代码无效。
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
现在应该具有最后插入行的ID,但由于某种原因它是nil
。
我尝试在控制台中运行ActiveRecord::Base.connection.insert(sql)
并且它有效(即,它返回了我想要的ID)。
任何人都知道这里出了什么问题?我需要更改一些设置以允许postgres返回最后一个ID吗?
答案 0 :(得分: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