Devise User ID skips several numbers in auto incre

2019-08-14 03:18发布

问题:

I have section of code that programmatically creates a new devise user:

    user = User.new
    user.username = params[:username]
    user.email = params[:email]
    user.password = params[:password]

    if user.save
        render :json => user
    else
        render :json => user.errors
    end

I have recently noticed that the user id has skipped about 30 numbers in my records.

Looking at my records I have:

Any idea what might have caused this huge gap in the increment? Users have no way to delete their account.

回答1:

If you're deployed on Heroku, you're using Postgres. In Postgres, primary keys ids are allocated just once in an linear, autoincremented sequence. But in the event that a transaction is rolled back, the allocated id will still be marked as used and will not be allocated again.

It's impossible to tell definitively, but my guess is that the creation of all users between 30 and 61 were rolled back due to some transactional error. You may want to crosscheck against your repository commits to see whether you made any modifications to your User model that might correspond to the time frame during which no users were committed to the DB.

Basically, things were working at one point, then they broke, and now they're working again. Check the period between User.find(29).created_at and User.find(62).created_at and see whether any commits may have impacted your model.