I’d like to be able to return objects in the order they were created. Obviously I could use the created_at field to do this but this will not work in my test scripts where I have stubbed out Time.zone.now to always return the same time.
Does AR guarantee that the next id will always be greater than the last object or is there the possibility that it will reuse deleted ids. I’m pretty sure that databases offer both types of functionality but what does Rails choose by default?
EDIT:
Testing with the SQLite driver suggest that it is monotonic. Even if I delete all the records in the table, close the session, open the session and create more records the id’s of the new records are given id’s greater than those of the previous deleted objects. However I don’t want to rely on empircal evidence here. If someone has a definitive answer on the design intention of ActiveRecord that would be appreciated.
There is no guarantee that the IDs will match the insertion order but you’ll usually be safe.
For example: if you have a really large database that has accumulated a lot of holes due to deleted items, you might compact it and reset the underlying sequences (or whatever your database uses to generate the IDs) to recover some unused values. Rails just uses the database’s implementation but your DBA (or you with your DBA hat on) is not so constrained.
The IDs should be monotonically increasing over the short term unless you end up using some sort of hateful database that wants you to suffer.