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

前端 未结 13 1309
臣服心动
臣服心动 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 07:03

    If you want to be sure no one else can take the 'new' index, you should lock the table. By using something like:

    ActiveRecord::Base.connection.execute("LOCK TABLES table_name WRITE")
    

    and

    ActiveRecord::Base.connection.execute("UNLOCK TABLES")
    

    But this is specific for each database engine.

    The only correct answer for a sequential id column is:

    YourModel.maximum(:id)+1
    

    If you sort your model in a default scope, last and first will depend on that order.

提交回复
热议问题