Skip to content

Instantly share code, notes, and snippets.

@townofdon
Created October 5, 2020 18:40
Show Gist options
  • Save townofdon/f48b9a0ddebeda1219eca72dedf7d0f1 to your computer and use it in GitHub Desktop.
Save townofdon/f48b9a0ddebeda1219eca72dedf7d0f1 to your computer and use it in GitHub Desktop.
Rails Postgresql - reset auto increment to latest ids
# 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