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
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