When using raw ActiveRecord :: Base.connection (), how do I get the last inserted primary key value?

This code works on my local RoR / Windows 7 (64-bit):

sql = ActiveRecord::Base.connection()
last_pk = sql.insert("insert into manual (name) values ('hello new value')")
puts 'last_pk=', last_pk

but always displays "0."

For various reasons, I cannot use ActiveRecord in this situation.

(Note: the above code works fine on my shared host. Also note: I had to replace mysql5 \ bin \ libmySQL.dll with another DLL with another answer at StackOverflow.com to get ANY database connection to work.)

+3
source share
2 answers

If in doubt, get it from mysql:

SELECT LAST_INSERT_ID()

, . , .

+1

, insert_sql insert, ..

last_pk = sql.insert_sql("insert into manual (name) values ('hello new value')")
puts "last_pk=#{last_pk}"

, insert_sql . insert_sql mysql_adapter.rb.

def insert_sql(sql, name = nil, pk = nil, id_value = nil, sequence_name = nil)
  super sql, name
  id_value || @connection.insert_id
end
+1

Source: https://habr.com/ru/post/1735750/


All Articles