How do I get ActiveRecord to show the next id (last + 1) in Ruby on Rails?

前端 未结 13 1295
臣服心动
臣服心动 2020-12-05 06:33

Is there a compact way with ActiveRecord to query for what id it\'s going to use next if an object was going to be persisted to the database? In SQL, a query like this would

13条回答
  •  情书的邮戳
    2020-12-05 06:55

    If no one else is using the table (otherwise you would have to use locking), you could get the autoincrement value from MySQL, the SQL command is

    SELECT auto_increment FROM information_schema.tables 
    WHERE table_schema = 'db_name' AND table_name = 'table_name';
    

    and the Rails command would be

    ActiveRecord::Base.connection.execute("SELECT auto_increment 
         FROM information_schema.tables 
         WHERE table_schema = 'db_name' AND table_name = 'table_name';").first[0]
    

提交回复
热议问题