Rails ActiveRecord:获取原始插入的id

bgc*_*ode 6 sql activerecord ruby-on-rails octopus

sql = DmozCategory.send(:sanitize_sql_array, ["INSERT INTO dmoz_categories (id, dmoz_category_title, dmoz_category_name, dmoz_category_description, created_at, updated_at, dmoz_category_lastupdate) VALUES (?, ?, ?, ?, NOW(), NOW(), ?)", result['catid'], result['title'], result['name'], result['description'], result['lastupdate']])

res = DmozCategory.connection.execute(sql)
$stderr.puts res.inspect
Run Code Online (Sandbox Code Playgroud)

res总是nil,即使我可以看到DmozCategory插入到数据库中.如何获得id以下我的插入?

我意识到我可以使用另一个SQL查询SELECT LAST_INSERT_ID()来获取ID,但我想知道是否有办法通过Rails获取id.中号

背景:使用Rails 2.3.14

更新:嗯,我认为问题在于我使用的一个名为Octopus的插件.很抱歉打折你的一些答案..看起来我需要找到如何使用此插件获取插入的最后一个ID.我的完整系数:

desc "load all categories from dmoz" # With this one we're loading all the 'structure' table in, not the parent-child relationships.
  task :load_categories_from_dmoz, [ :offset, :limit ] => :environment do |t, args|
    offset = !args[:offset].blank? ? args[:offset].to_i : 0 # Take offset from args.  Default of 0
    limit = !args[:limit].blank? ? args[:limit].to_i : 1 # Take limit from args.  Default of 1
    ActiveRecord::Base.octopus_establish_connection(:adapter=> "mysql", :host=> "localhost", :database => "dmoz", :username => "dmoz", :password => "dmoz")

    results = ActiveRecord::Base.connection.select_all("SELECT * FROM structure LIMIT #{ offset }, #{ limit }") # Fetches it directly from the dmoz database.
    count = offset
    conn = ActiveRecord::Base.octopus_establish_connection(:adapter=> "mysql", :host=> "localhost", :database => "talon_development", :username => "rails_shadow", :password => "husky")
    results.each do |result|
      if count % 1000 == 0
        puts count
      end
      count +=1

      begin
        sql = DmozCategory.send(:sanitize_sql_array, ["INSERT INTO dmoz_categories (id, dmoz_category_title, dmoz_category_name, dmoz_category_description, created_at, updated_at, dmoz_category_lastupdate) VALUES (?, ?, ?, ?, NOW(), NOW(), ?)", result['catid'], result['title'], result['name'], result['description'], result['lastupdate']]) #We leave parent_id NULL for the next task to handle relationships

        DmozCategory.connection.execute(sql) #doesn't get the ID..

      end
    end
  end
Run Code Online (Sandbox Code Playgroud)

Fre*_*ung 14

一般而不是使用connection.execute,使用connection.insert

这将返回最后插入行的生成id.它是如何做到这一点依赖于数据库.在MySQL上,最后一个插入ID是连接的属性.在Postgres上,一个'returns'子句被附加到查询中(对于postgres的旧版本,后备会询问序列的最后一个id).

使用insert而不是execute也会清除rails查询缓存.

至少在MySQL上,即使你自己设置了id,这也会有效.


小智 -1

假设您使用 MYSQL 并且表自动增量,您可以使用:

SELECT LAST_INSERT_ID()
Run Code Online (Sandbox Code Playgroud)

按照提示操作,获取表中最后插入的 ID。这会向您的代码添加另一个查询,但它似乎坚持使用原始 SQL。