Created
October 5, 2020 18:40
-
-
Save townofdon/f48b9a0ddebeda1219eca72dedf7d0f1 to your computer and use it in GitHub Desktop.
Rails Postgresql - reset auto increment to latest ids
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# stolen from: http://blog.joncairns.com/2013/01/reset-postgresql-auto-increment-value-in-rails/ | |
TABLES_TO_IGNORE = [] | |
ActiveRecord::Base.connection.tables.each do |table| | |
next if TABLES_TO_IGNORE.include?(table) | |
result = ActiveRecord::Base.connection.execute("SELECT id FROM #{table} ORDER BY id DESC LIMIT 1") | |
if result.any? | |
ai_val = result.first['id'].to_i + 1 | |
puts "Resetting auto increment ID for #{table} to #{ai_val}" | |
ActiveRecord::Base.connection.execute("ALTER SEQUENCE #{table}_id_seq RESTART WITH #{ai_val}") | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment