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を取得する方法を見つける必要があるようです。私の完全なコー:
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