【发布时间】:2012-06-13 23:26:24
【问题描述】:
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
res 始终是nil,即使我可以看到 DmozCategory 插入到数据库中。如何在我的插入后获得id?
我意识到我可以使用另一个 SQL 查询 SELECT LAST_INSERT_ID() 来获取 ID,但我想知道是否有办法通过 Rails 获取 ID。 M
背景:使用 Rails 2.3.14
更新:嗯,我认为问题出在我使用的名为 Octopus 的插件上。抱歉打折了您的一些答案。看来我需要找到如何使用此插件获取插入的最后一个 id。我完整的 coe:
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
【问题讨论】:
-
试试
exec_query和last_inserted_id(res) -
@YuriBarbashov 我认为 Rails 2.3.14 中没有这种功能?
-
你不是自己插入id吗?
INSERT INTO dmoz_categories (id, ...) VALUES (?, ...), result['catid'], ...? -
是的,但我想稍后检查它是否有效。不确定是不是。
标签: sql ruby-on-rails activerecord octopus