Does ruby support a way to retrieve the id for the last inserted row simliar to php's 开发者_开发知识库mysql_insert_id()
method for mysql databases?
It's pretty much the same in ruby, except that the mysql connection is wrapped by an object and that the library is available trough rubygems ( gem install mysql
)
require 'mysql'
db = Mysql.connect(hostname, username, password, databasename)
db.execute("INSERT INTO mytable VALUES 1,2,3");
db.insert_id
# => last inserted id
see http://www.tmtm.org/en/mysql/ruby/
Usually you don't do that and rely on a sql abstraction library like ActieRecord, DataMapper, Sequel, DBI, ... all of them have this method available but under different modules.
you can always use SELECT last_insert_id()
query instead.
Why would you need that? Chances are that you're not using ActiveRecord to its full power. However, you can access the id of a created record by just accessing @record.id
.
I would recommend to not use plain SQL syntax in Rails...
Update: Sorry, just realized you may in fact NOT be using ActiveRecord. Of course it's feasible to use the suggested SELECT
syntax then (and it's the right way to obtain this value). Personally, I'd still prefer to use ActiveRecord.
精彩评论