Created
July 5, 2018 06:57
-
-
Save dekaikiwi/5eb9003d5ec40257cfdcbd12810b1dc5 to your computer and use it in GitHub Desktop.
For when you forget to run RAILS_ENV=test bundle exec rspec
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
# 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