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

前端 未结 13 1232
臣服心动
臣服心动 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:15

    This is an old question, but none of the other answers work if you have deleted the last record:

    Model.last.id #=> 10
    Model.last.destroy
    Model.last.id #=> 9, so (Model.last.id + 1) would be 10... but...
    Model.create  #=> 11, your next id was actually 11
    

    I solved the problem using the following approach:

    current_value = ActiveRecord::Base.connection.execute("SELECT currval('models_id_seq')").first['currval'].to_i
    Model.last.id #=> 10
    Model.last.destroy
    Model.last.id #=> 9
    current_value + 1 #=> 11
    
    0 讨论(0)
提交回复
热议问题