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

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

    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
    

提交回复
热议问题