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

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

    I came to this SO question because I wanted to be able to predict the id of a model created in my test suite (the id was then used a REST request to an external service and I needed to predict the exact value to mock the request).

    I found that Model.maximum(:id).next, although elegant, doesn't work in a rails testing environment with transactional fixtures since there are usually no records in the db so it will simply return nil.

    Transactional fixtures make the issue extra tricky since the auto increment field ascends even when there aren't any records in the db. Furthermore using an ALTER TABLE ***your_table_name*** AUTO_INCREMENT = 100 breaks the transaction your tests are in because it requires its own transaction.

    What I did to solve this was to create a new object and add 1 to its id:

    let!(:my_model_next_id) { FactoryBot.create(:my_model).id + 1 }
    

    Although somewhat hacky (and slightly inefficient on your db since you create an extra object for the sake of its id), it doesn't do anything goofy to the transaction and works reliably in a testing environment with no records (unless your tests run in parallel with access to the same db...in which case: race conditions...maybe?).

提交回复
热议问题