Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ruby-fu-ninja/4499099 to your computer and use it in GitHub Desktop.
Save ruby-fu-ninja/4499099 to your computer and use it in GitHub Desktop.
Update Postgres id sequences on all of your Rails models
Dir[Rails.root.join('app', 'models', '*')].each do |path|
file = File.basename(path, '.rb')
begin
klass = file.classify.constantize
if klass.respond_to?(:select)
max_id = klass.maximum(:id).to_i + 1
sequence = ActiveRecord::Base.connection.execute("SELECT nextval('#{klass.table_name}_id_seq')").first['nextval'].to_i
if sequence <= max_id
puts "Updating sequence for #{klass.table_name}"
ActiveRecord::Base.connection.execute("SELECT setval('#{klass.table_name}_id_seq', (SELECT MAX(id) FROM #{klass.table_name}))")
end
end
rescue ActiveRecord::StatementInvalid
puts "Something was wrong with SQL in #{File.basename(file)}"
rescue NameError
puts "#{File.basename(file)} does not exist"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment