If you create say 5 User records then destroy them all. The next User entry in the database that’s created will have an id of 6. How does rails know to give this new row an id of 6 and not 1? I ran into this issue because I was trying to “guess” what the next id for a User record would be but ran into trouble with the above scenario. I’m currently using postgresql but I don’t believe this functionality would be database dependent? Thanks a bunch!
If you create say 5 User records then destroy them all. The next User
Share
This is database dependent. When you insert, most databases returns the id for the inserted row. In PostgreSQL, you have what you call a “sequence” that keeps the current/next id number (not sure which). Other databases may vary.
See: https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb#L726
This is where it finds the current sequence: https://github.com/rails/rails/blob/master/activerecord/lib/active_record/connection_adapters/postgresql_adapter.rb#L1513