rails postgres插入 [英] rails postgres insert

查看:98
本文介绍了rails postgres插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试按照乔纳芬在 http://www.genesx.com/2012/06/import-csv-files-100x-faster-in-rails-3/

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/

我试图从postgres获取最后一个插入的索引,但是由于某种原因,代码无法正常工作。

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 现在应该具有最后插入的行的ID,但是由于某些原因它是 nil

booking_id should now have the id of the last inserted row, but for some reason it is nil.

我尝试在控制台中运行 ActiveRecord :: Base.connection.insert(sql)并成功运行(即,它返回了我想要的ID)。

I tried running ActiveRecord::Base.connection.insert(sql) in the console and it worked (i.e., it returned the id I wanted).

有人知道这里出了什么问题吗?我是否需要更改某些设置以允许postgres返回最后一个ID?

Anyone know what's going wrong here? Is there some setting I need to change to allow postgres to return the last id?

推荐答案

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

这篇关于rails postgres插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆