Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dekaikiwi/5eb9003d5ec40257cfdcbd12810b1dc5 to your computer and use it in GitHub Desktop.
Save dekaikiwi/5eb9003d5ec40257cfdcbd12810b1dc5 to your computer and use it in GitHub Desktop.
For when you forget to run RAILS_ENV=test bundle exec rspec
# https://stackoverflow.com/questions/28639439/rails-repeated-activerecordrecordnotunique-when-creating-objects-with-postgre?rq=1
ActiveRecord::Base.descendants.each do |model|
unless model.attribute_names.include?('id')
Rails.logger.debug "Not resetting #{model}, which lacks an ID column"
next
end
begin
max_id = model.maximum(:id).to_i + 1
result = ActiveRecord::Base.connection.execute(
"ALTER SEQUENCE #{model.table_name}_id_seq RESTART #{max_id};"
)
Rails.logger.info "Reset #{model} sequence to #{max_id}"
rescue => e
Rails.logger.error "Error resetting #{model} sequence: #{e.class.name}/#{e.message}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment