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
Get the largest id on the table
YourModel.maximum(:id)
This will run the following sql
SELECT MAX("your_models"."id") AS max_id FROM "your_models"
Convert the result to an integer by calling to_i
. This is important as for an empty table the above max command will return nil
. Fortunately nil.to_i
returns 0
.
Now to get the next available id, just add 1 +
1`
The final result:
YourModal.maximum(:id).to_i+1